当IsEnabled设置为false时,WPF ComboBox SelectedIndex会更改

时间:2010-09-29 13:07:43

标签: .net wpf xaml mvvm combobox

我正在使用MVVM模式创建一个应用程序,并且我有一个包含ComboBox的视图。

<Controls:SettingsComboBox x:Name="Setting"
    SelectedIndex="{Binding SteeringIndex, Mode=TwoWay}"
    IsEnabled="{Binding SteerAttached, Mode=TwoWay}">
    <ComboBoxItem Content="{Binding Path=on, Source={x:Static Localization:CultureResources.ObjectDataProvider}}"/>
    <ComboBoxItem Content="{Binding Path=off, Source={x:Static Localization:CultureResources.ObjectDataProvider}}"/>
</Controls:SettingsComboBox>

因此SelectedIndexIsEnabled绑定到视图模型,该模型从设置文件中检索值或从外部事件中获取值。

如果SelectedIndex为0(打开)且IsEnabled设置为false,则一切正常。如果SelectedIndex为1(关闭)且IsEnabled设置为false,则SelectedIndex会以某种方式设置为-1,从而导致空组合框。

为什么会发生这种情况,我该如何解决?我可以在收到事件时将SelectedIndex设置回来更改IsEnabled属性,但是当它被禁用时仍会离开并清空组合框,这样就不能真正作为解决方案。

1 个答案:

答案 0 :(得分:1)

在组合框上设置IsEnabled不会更改其SelectedIndex属性。代码中的某些内容(此处未显示)正在执行此操作,可能是您的VM。问题,为什么你为IsEnabled做双向绑定?你真的想在组合框上的IsEnabled改变时更新SteerAttached吗?

下面的代码让您可以使用启用/禁用组合框并更改所选索引。正如您所看到的,这些属性彼此独立。

<ComboBox
    SelectedIndex="{Binding Path=Value, ElementName=_slider, Mode=TwoWay}" 
    IsEnabled="{Binding IsChecked, ElementName=_checkBox}">
    <ComboBoxItem>AAA</ComboBoxItem>
    <ComboBoxItem>BBB</ComboBoxItem>
    <ComboBoxItem>CCC</ComboBoxItem>
</ComboBox>

<Slider Name="_slider" IsSnapToTickEnabled="True" TickFrequency="1" Minimum="0" Maximum="2" Width="30"/>

<CheckBox Name="_checkBox" />

相关问题