Rati_Ge
Rati_Ge

Reputation: 1270

WPF binding And DataContext

I have a situation where my view has a DataContext bound to the ViewModel but one of my controls inside the view has its DataContext Set to a property of the ViewModel. The first time I change that ViewModel, it shows the changes but after that, if I change property inside the ViewModel no changes are reflected back to the view.

//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);
    }

 }

Upvotes: 0

Views: 607

Answers (1)

decyclone
decyclone

Reputation: 30830

Explanation:

This is the classic case of not implementing INotifyPropertyChanged interface.

When you change the value of FlashMessage there is no way for the UI to know that. So, to let the UI know, you raise PropertyChanged event with the property name ("FlashMessage" in your case).

Once you implement INotifyPropertyChanged interface and notify property change for FlashMessage it should workout just fine.

Example:

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");
        }
    } 
}

-EDIT-

Try changing your code from following:

FlashMessage = null;   
FlashMessage = new FlashMessageModel { Message = obj.Message, FlashType = obj.FlashType };   
RaisePropertyChanged(() => FlashMessage);   

to following:

FlashMessage.Message = obj.Message;
FlashMessage.FlashType = obj.FlashType;

Upvotes: 1

Related Questions