我正在使用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>
Run Code Online (Sandbox Code Playgroud)
这是我的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
}
}
Run Code Online (Sandbox Code Playgroud)
在我的模型中,我在调用"开始"命令时更改标签.
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
}
}
Run Code Online (Sandbox Code Playgroud)
问题是在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;
}
}
Run Code Online (Sandbox Code Playgroud)
我们的想法是按钮的点击应该在视图模型中处理,该视图模型负责与模型的通信.此外,它还会根据模型的当前状态相应地更新属性.
| 归档时间: |
|
| 查看次数: |
546 次 |
| 最近记录: |