【问题标题】:SelectedIndex DataTrigger not working in ComboboxSelectedIndex DataTrigger 在组合框中不起作用
【发布时间】:2015-02-21 12:50:06
【问题描述】:

我想要做的是,如果一个组合框只有 1 个项目,那么它会被 预选。我尝试使用 DataTriggers 但它不适用于 'SelectedIndex' 属性。但是当我将 'IsEnabled' 属性设置为 false 时,它的工作并禁用组合框。

下面是我的代码:

<ComboBox  Name="WarehouseCombo" 
      ItemsSource="{Binding Path=WarehouseList}"
      SelectedValue="{Binding Warehouse,Mode=TwoWay}"
      Text="{Binding Path=TxtWarehouse,Mode=TwoWay}">
        <ComboBox.Style>
              <Style TargetType="{x:Type ComboBox}">
                    <Style.Triggers>
                         <DataTrigger
                              Binding="{Binding Path=Items.Count, ElementName=WarehouseCombo}" Value="1">
                                  <Setter Property="SelectedIndex" Value="0" />
                          </DataTrigger>
                     </Style.Triggers>
               </Style>
         </ComboBox.Style>
 </ComboBox>

请帮助我了解为什么会在“SelectedIndex”案例中发生这种情况。

【问题讨论】:

    标签: c# wpf combobox datatrigger


    【解决方案1】:

    不要使用SelectedIndex 属性。相反,请使用 SelectedItem 属性。满足您的要求的一种方法是为您的数据收集声明一个基类。试试这样的:

    public WarehouseList : ObservableCollection<WarehouseItems>
    {
        private T currentItem;
    
        public WarehouseList() { }
    
        public T CurrentItem { get; set; } // Implement INotifyPropertyChanged here
    
        public new void Add(T item)
        {
            base.Add(item);
            if (Count == 1) CurrentItem = item;
        }
    }
    

    现在,如果您使用此类而不是标准集合,它将自动将第一项设置为选中。要在 UI 中完成这项工作,您只需将此属性数据绑定到 SelectedItem 属性,如下所示:

    <DataGrid ItemsSource="{Binding WarehouseList}" 
        SelectedItem="{Binding WarehouseList.CurrentItem}" />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-03
      • 2012-08-07
      • 2012-07-11
      • 2012-03-19
      • 2014-12-23
      • 2013-10-15
      • 1970-01-01
      • 2017-07-18
      相关资源
      最近更新 更多