当绑定的VM属性更改时,WPF MVVM控件不会更新

时间:2016-07-13 10:27:42

标签: c# wpf mvvm prism

我正在使用Prism Framework编写MVVM应用程序。当属性值更改时,我无法更新标签。当我创建模型并为属性分配初始值时,绑定到它的标签会更新。但是当我在应用程序生命周期内更改属性时,标签将不会更新其内容。

这是我的xaml:

<Window x:Class="Project.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="700" Width="700">
    <DockPanel LastChildFill="True">
            <Button x:Name="btnStart" Command="{Binding Path=Start}" Content="StartProcess"/>

            <GroupBox Header="Current Operation">
                <Label x:Name="lblCurrentOperation" Content="{ Binding  CurrentOperationLabel, UpdateSourceTrigger=PropertyChanged}"/>
            </GroupBox>
    </DockPanel>
</Window>

这是我的ViewModel:

public class MyModelViewModel : BindableBase
{
    private MyModel model;
    private string currentOpeartion;

    public DelegateCommand Start { get; private set; }

    public string CurrentOperationLabel
    {
        get { return currentOpeartion; }
        set { SetProperty(ref currentOpeartion, value); }
    }

    public MyModelViewModel ()
    {
        model = new MyModel ();

        Start  = new DelegateCommand (model.Start);
        CurrentOperationLabel = model.CurrentOperation; //Bind model to the ViewModel
    }   
}

在我的模型中,我在调用“开始”命令时更改标签。

public class MyModel
{
    public string CurrentOperation { get; set; }

    public MyModel()
    {
        CurrentOperation = "aaa"; //This will make the label show "aaa"
    }

    public void Start()
    {
        CurrentOperation = "new label"; //This should alter the Label in the view, but it doesn't
    }
}

1 个答案:

答案 0 :(得分:5)

问题在于,在Start方法中,您修改了模型的属性(即CurrentOperation),而不是视图模型的属性(即CurrentOperationLabel)。 XAML对模型一无所知,因为它绑定到视图模型。换句话说,当您修改MyModel.CurrentOperation属性时,XAML不会收到有关此事实的通知。

要解决此问题,您应该更改代码的结构。您需要在更新模型后刷新视图模型。我的建议是以这种方式修改MyModelViewModel

public class MyModelViewModel : BindableBase
{
      //...

      public void InnerStart()
      {
          model.Start();
          //Refresh the view model from the model
      }

      public MyModelViewModel ()
      {
        model = new MyModel ();

        Start  = InnerStart;
        CurrentOperationLabel = model.CurrentOperation; 
    }   
}

这个想法是应该在视图模型中处理按钮的点击,该模型负责与模型的通信。此外,它还会根据模型的当前状态相应地更新属性。