开发者

Silverlight TwoWay-bound ComboBox setting values to NULL

Before I explain my issue, consider the following object:

Character.cs

-> AnimationControlSettings.cs

..  -> UpControlType (string)

..  -> AvailableControlTypes (List<string>)

The relevant properties in my ViewModel:

Character SelectedCharacter
ObservableCollection<Character> Characters

I have a simple View where you select a character using a ComboBox. The ComboBox's SelectedItem is TwoWay-bound to the ViewModel's SelectedCharacter property. There are other textboxes/checkboxes (also two-way bound to various properties of SelectedCharacter) that maintain their values properly as I switch between Characters.

The problem exists in the ComboBox bound to the UpControlType property:

<ComboBox x:Name="lstUpControlTypes" 
        ItemsSource="{Binding Path=SelectedCharacter.AnimationControlSettings.Av开发者_运维百科ailableControlTypes}" 
        SelectedItem="{Binding Path=SelectedCharacter.AnimationControlSettings.UpControlType, Mode=TwoWay}">
</ComboBox>

Initial values are displayed in this ComboBox correctly but as soon as I switch from CharacterA to CharacterB, CharacterA's UpControl property is set to NULL and I have no idea why.

Here is a barebones repro of this exact issue (VS2010, SL4): http://www.checksumlabs.com/source/TwoWayBindingWorkshop.zip

If you run that solution you'll see that the Name property persists as you switch Characters but the UpControlType value's getting set to NULL.

Am I missing something obvious here?


You are binding the items source of the third combo box to a property inside the SelectedCharacter, like this:

ItemsSource="{Binding SelectedCharacter.AnimationControlSettings.AvailableControlTypes}" 

This means that when SelectedCharacter changes the items source for that combo box will be reset and this activates the two way binding you set in the SelectedItem of the same combo box, setting your property to null:

SelectedItem="{Binding SelectedCharacter.AnimationControlSettings.UpControlType, Mode=TwoWay}"

I was able to fix the issue by moving the property AvailableControlTypes to the CharacterViewModel class, which means that when you change the character, the available types remain the same. If this is acceptable in your situation, it will fix your problem:

            <ComboBox x:Name="lstUpControlTypes" 
                      ItemsSource="{Binding AvailableControlTypes}" 
                      SelectedItem="{Binding     SelectedCharacter.AnimationControlSettings.UpControlType, Mode=TwoWay}" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜