2
votes

I have a Datagrid with a list binded to ItemsSource and the SelectedItem is binded a single object of this list. My ViewModel implements INotifyPropertyChanged.

The binding works fine, except when there's a variable (canSelectOtherObject = false) that prevents myObject of changing it's value. Even thought myObject doesn't modify it's value, the datagrid on the View selects other object. How can I prevent this?

View:

<DataGrid ItemsSource="{Binding MyObjectList}" SelectedItem="{Binding MyObjectSelected, Mode=TwoWay}">

ViewModel:

private ObservableCollection<MyObject> myObjectList;
private MyObject myObjectSelected;
private bool canSelectOtherObject;

public ObservableCollection<MyObject> MyObjectList
{
    get { return myObjectList; }
    set { myObjectList = value; }
}

public MyObject MyObjectSelected
{
    get { return myObjectSelected; }
    set
    {
        if(canSelectOtherObject)
        {
            myObjectSelected = value;
            OnPropertyChanged("MyObjectSelected");
        }
    }
}

Thanks!

1
Try moving the OnPropertyChanged outside of the if statement, this should cause the binding to refresh and reselect the SelectedItem you expect. However it may look a bit odd to the user.ndonohoe
I tried that but still had no success.Natan
Try setting the IsSynchronizedWithCurrentItem property to true? msdn.microsoft.com/en-us/library/…ndonohoe

1 Answers

0
votes

INotifyPropertyChanged is used to notify the UI to update bindings when the properties of an object change, I think you are describing a situation where the object itself changes.

Given your binding:

<DataGrid ItemsSource="{Binding MicrophoneList}" SelectedItem="{Binding MicrophoneSelected, Mode=TwoWay}">

It's the difference between updating one of the properties of the selected microphone (would require INotifyPropertyChanged), and changing SelectedItem to a different microphone altogether (binding updates whether you notify or not).