Aug 11, 2010

Silverlight 3 Trap : OneWayToSource

Silverlight is missing some details you may be using in WPF. One of them is the missing data binding mode OneWayToSource. Another one is the missing SelectionChanged command of a ComboBox. Both created a funny behavior in my current project.

image

I have a ViewModel property

public string Selected

{

    get

    {

        return this._selected;

    }

    set

    {

        this._selected = value;

        this.RaisePropertyChanged("Selected");

    }

}

and two ComboBox TwoWay (OneWayToSource does not exist) binding on it with SelectedItem

<ComboBox Name="c1" mycmd:SelectionChangedCommand.Command="{Binding C1SelectionChangedCommand}" ItemsSource="{Binding Selections}" SelectedItem="{Binding Selected, Mode=TwoWay}" />

<ComboBox Name="c2" mycmd:SelectionChangedCommand.Command="{Binding C2SelectionChangedCommand}" ItemsSource="{Binding Selections}" SelectedItem="{Binding Selected, Mode=TwoWay}" />

The funny thing was, that when I made a selection on combo box c1 the command handler of my c2 fired (too) – due to the this.RaisePropertyChanged("Selected") above:

- c1 copies the SelectedItem from the target to the source

- the source property raises the property changed event and

- copies the Selected property value to the other c2 target

- c2 fires the SelectionChanged command

Et voilĂ , your in the Guatemala City trap…it would be better to have more fine-grained data binding control with OneWayToSource in the first place.