0

我有一种情况,我的视图有一个绑定到 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);
    }

 }
4

1 回答 1

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;
于 2012-10-18T17:38:39.937 回答