2

我想通过使用 DataTrigger 将 ComboBox 的 SelectedIndex 设置为 0,当它绑定的 SelectedItem 为空时。但它不起作用。我哪里错了?

xml如下:

<ComboBox SelectedItem="{Binding MyObject.color_master, Mode=TwoWay}"  
          ItemsSource="{Binding  MyEntities.color_master}"
          DislayMemberPath="COLOR_DESCRIPTION" >
 <ComboBox.Style>
  <Style TargetType="ComboBox">
    <Style.Triggers>                                
      <DataTrigger Binding="{Binding Path=MyObject.color_master}" Value="{x:Null}">
          <Setter Property="SelectedIndex" Value="0" />
       </DataTrigger>                                
      </Style.Triggers>
  </Style>
 </ComboBox.Style>
</ComboBox>

这里MyObject.color_master,但 DataTrigger 仍然无法正常工作!

我的要求很简单,当组合框中没有选择任何内容时,我希望选择第一项。

4

1 回答 1

1

这只是一个猜测,但是当您同时使用两者SelectedItemSelectedIndex创建对 WPF 实现的依赖时:“谁赢了?” 是一个实现的东西。即使它被记录在某个地方,也意味着每个开发人员都知道这个顺序(这也不好,因为你永远不确定谁会维护你的代码)。

我认为您可以在这里做的最简单的事情是使用单个绑定到ViewModelSelectedColorIndex属性并让ViewModel计算基于 的值color_master。所以最终结果将如下所示:

<ComboBox SelectedIndex="{Binding MyObjectViewModel.SelectedColorIndex, Mode=TwoWay}"  
          ItemsSource="{Binding  MyEntities.color_master}"
          DislayMemberPath="COLOR_DESCRIPTION" >
</ComboBox>

更新:既然你说你的视图模型不能被触摸,这里是另一种选择。编写您自己的 IValueConverter ,它将接受一个MyObject.color_master并将其转换为索引:

<ComboBox SelectedIndex="{Binding MyObject.color_master, Mode=TwoWay, Converter={StaticResouce ColorMasterToIndexConverter}}"  
          ItemsSource="{Binding  MyEntities.color_master}"
          DislayMemberPath="COLOR_DESCRIPTION" >
</ComboBox>

ColorMasterToIndexConverter可访问资源字典中定义的位置(例如,在同一个UserControl.Resources集合中)。

于 2011-02-07T13:03:23.177 回答