C# SelectedIndex数据触发器在组合框中不工作
我想做的是,如果一个组合框只有1个项目,那么它将被预先选择。我尝试使用数据触发器,但它不适用于“SelectedIndex”属性。但当我将“IsEnabled”属性设置为false时,它将工作并禁用组合框 下面是我的代码:C# SelectedIndex数据触发器在组合框中不工作,c#,wpf,combobox,datatrigger,C#,Wpf,Combobox,Datatrigger,我想做的是,如果一个组合框只有1个项目,那么它将被预先选择。我尝试使用数据触发器,但它不适用于“SelectedIndex”属性。但当我将“IsEnabled”属性设置为false时,它将工作并禁用组合框 下面是我的代码: <ComboBox Name="WarehouseCombo" ItemsSource="{Binding Path=WarehouseList}" SelectedValue="{Binding Warehouse,Mode=TwoWay}
<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”案例中发生这种情况的原因。不要使用
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;
}
}
<DataGrid ItemsSource="{Binding WarehouseList}"
SelectedItem="{Binding WarehouseList.CurrentItem}" />