![](/img/trans.png)
[英]Refresh ObservableCollection<T> when a property in T changes - WPF MVVM
[英]WPF MVVM control won't update when its bound VM Property changes
我正在使用Prism Framework編寫MVVM應用程序。 屬性值更改時,我無法更新標簽。 當我創建模型並將初始值分配給Property時,綁定到它的標簽會更新。 但是,當我在應用程序生命周期內更改屬性時,標簽將不會更新其內容。
這是我的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
}
}
問題在於,在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;
}
}
想法是應該在視圖模型中處理按鈕的單擊,該視圖模型負責與模型進行通信。 另外,它根據模型的當前狀態相應地更新屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.