【问题标题】:C# Prism : Setting ViewModel property from a controller (MVVM)C# Prism:从控制器 (MVVM) 设置 ViewModel 属性
【发布时间】:2016-06-24 20:50:04
【问题描述】:

视图模型:

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 中

【问题讨论】:

  • 您确定您的_connectionView 实例是显示的那个吗?还有,当你注入了视图模型时,为什么还要使用ViewModelLocator
  • 移除了视图注入

标签: c# wpf mvvm prism


【解决方案1】:

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

【讨论】:

  • 可能只是 UI 没有更新...你必须实现 INotifyProperyChanged 才能更新 UI 吗?
  • 你是对的,它正在更新,只是没有在 UI 中显示
  • BindableBase 实现 INotifyPropertyChanged... 你应该确保你正在更新的视图模型实际上是绑定的。
【解决方案2】:

用户控件的DataContext 在UC 初始化时获取其值。然后,您获取 DataContext 的副本,将其转换为视图模型对象,并更改属性。我不相信 UC 在这种情况下会更新其原始 DataContext。

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

【讨论】:

    【解决方案3】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2023-01-07
      • 1970-01-01
      • 2011-07-17
      • 1970-01-01
      • 2011-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-29
      相关资源
      最近更新 更多