C# Prism:从控制器 (MVVM) 设置 ViewModel 属性

C# Prism : Setting ViewModel property from a controller (MVVM)

视图模型:

public class ConnectionStatusViewModel : BindableBase
{

    private string _txtConn;

    public string TextConn
    {
        get { return _txtConn; }
        set { SetProperty(ref _txtConn, value); }
    }
}

XAML:

<UserControl x:Class="k7Bot.Login.Views.ConnectionStatus"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:prism="http://www.codeplex.com/prism"
            prism:ViewModelLocator.AutoWireViewModel="True" Width="300">

    <Grid x:Name="LayoutRoot">    
        <Label Grid.Row="1" Margin="10,0,10,0">connected:</Label>
        <TextBlock Text="{Binding TextConn}"  Grid.Row="1" Grid.Column="1" Margin="10,0,10,0" Height="22" />
    </Grid>

</UserControl>

观点:

public partial class ConnectionStatus : UserControl
{
    public ConnectionStatus()
    {
        InitializeComponent();
    }
}

在另一个模块中,我有一个事件侦听器,最终运行此代码:

ConnectionStatusViewModel viewModel = _connectionView.DataContext as ConnectionStatusViewModel;
if (viewModel != null)
{
    viewModel.TextConn = "Testing 123";

}

代码运行但 TextConn 已更新且未显示在 UI

您确定 TextConn 不更新吗?因为它可以更新但显示无法更改。您应该实现 INotifyPropertyChanged 接口,并在对 TextConn 进行任何更改后调用已实现的 OnPropertyChanged("TextConn");或者你给函数起的任何名字。这将告诉 UI 该值已更改并且需要更新。

UserControl 的 DataContext 在 UC 初始化时获取其值。然后你得到一个 DataContext 的副本,将它转换为一个视图模型对象,并更改 属性。我不相信 UC 在这种情况下会更新其原始 DataContext。

可能您需要使用消息中介来传达不同模块之间的更改。

经过一些故障排除后,此代码有效,问题是我 运行 此代码:

ConnectionStatusViewModel viewModel = _connectionView.DataContext as ConnectionStatusViewModel;
if (viewModel != null)
{
    viewModel.TextConn = "Testing 123";

}

在实际激活视图之前。愚蠢,但也许它会帮助某人。