我的情况是我的视图有一个绑定到ViewModel的DataContext,但是我在视图中的一个控件将其DataContext设置为ViewModel的一个属性。我第一次更改ViewModel时,它会显示更改但在此之后,如果我在ViewModel中更改了属性,则没有任何更改会反映回视图。
//Somewhere inside my View
<TaicoControl:FlashMessage DataContext="{Binding FlashMessage}"
DockPanel.Dock="Top"
FadesOutAutomatically="True"
FontFamily="BPG Arial"
Message="{Binding Message}"
MessageType="{Binding FlashType}" />
//End of the View
public sealed class ShellViewModel : ViewModelBase
{
public FlashMessageModel FlashMessage { get; private set; }
protected override void SetupEvents()
{
RegisterForEvent<SystemBaloonRequiered>(OnBaloonRequest);
RegisterForEvent<FlashRequest>(OnFlashRequested);
base.SetupEvents();
}
#region Message Handlers
private void OnFlashRequested(FlashRequest obj)
{
FlashMessage = null;
FlashMessage = new FlashMessageModel { Message = obj.Message, FlashType = obj.FlashType };
RaisePropertyChanged(() => FlashMessage);
}
}
答案 0 :(得分:1)
这是未实现 INotifyPropertyChanged 界面的经典案例。
当您更改 FlashMessage 的值时,UI无法知道这一点。因此,为了让UI知道,您使用属性名称(在您的情况下为“FlashMessage”)引发 PropertyChanged 事件。
实施 INotifyPropertyChanged 界面并通知 FlashMessage 的属性更改后,它应该运动得很好。
public sealed class ShellViewModel : ViewModelBase, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
var temp = PropertyChanged;
if(temp != null)
{
temp(this, new PropertyChangedEventArgs(propertyName));
}
}
public FlashMessageModel _flashMessage;
public FlashMessageModel FlashMessage
{
get { return _flashMessage; }
private set
{
_flashMessage = value;
RaisePropertyChanged("FlashMessage");
}
}
}
- 编辑 -
尝试更改以下代码:
FlashMessage = null;
FlashMessage = new FlashMessageModel { Message = obj.Message, FlashType = obj.FlashType };
RaisePropertyChanged(() => FlashMessage);
以下:
FlashMessage.Message = obj.Message;
FlashMessage.FlashType = obj.FlashType;