wpf组合框默认值

时间:2016-07-14 18:28:05

标签: wpf combobox datatrigger

当SelectedValue为Null时,我正在尝试将组合框所选项目默认为index = 0。数据触发器有什么问题? 错误:SelectedIndex未识别属性

 <ComboBox x:Name="ACombobox" ItemsSource="{Binding Mode=OneWay, Source={StaticResource AList}}" 
                    DisplayMemberPath="TypeName" SelectedValuePath="TypeName" 
                    SelectedValue="{Binding  AnObj.Type, Mode=TwoWay}"  >
                        <ComboBox.Triggers>
                            <DataTrigger Binding="{Binding}" Value="{x:Null}">
                                <Setter Property="SelectedIndex" Value="0" />
                            </DataTrigger>
                        </ComboBox.Triggers>
                    </ComboBox>

1 个答案:

答案 0 :(得分:1)

您应该通过创建类似下面的样式触发器

来实现
<ComboBox x:Name="ACombobox" ItemsSource="{Binding Mode=OneWay, Source={StaticResource AList}}" 
                DisplayMemberPath="TypeName" SelectedValuePath="TypeName" 
                SelectedValue="{Binding  AnObj.Type, Mode=TwoWay}"  >
    <Style TargetType="ComboBox">
        <Style.Triggers>
            <DataTrigger Binding="{Binding}" Value="{x:Null}">
                <Setter Property="SelectedIndex" Value="0" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</ComboBox>

错误说明it does not have a qualifying type name因此,当您设置TargetType="ComboBox"

时,通过创建适用于Combobox的样式
<ComboBox x:Name="ACombobox" ItemsSource="{Binding AList}"
            DisplayMemberPath="TypeName" SelectedValuePath="TypeName" 
            SelectedValue="{Binding  AnObj.Type, Mode=TwoWay}"   >
  <ComboBox.Resources>
    <Style TargetType="ComboBox">
        <Style.Triggers>
            <DataTrigger Binding="{Binding SelectedItem}" Value="{x:Null}">
                <Setter Property="SelectedIndex" Value="0" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
  </ComboBox.Resources>
</ComboBox>

这适合我。

StaticResource的示例

     <Window.Resources>
        <x:Array x:Key="StringList" Type="System:String">
            <System:String>Line 1</System:String>
            <System:String>Line 2</System:String>
            <System:String>Line 3</System:String>
            <System:String>Line 4</System:String>
       </x:Array>       
    </Window.Resources>
    <ComboBox ItemsSource="{StaticResource StringList}" >
      <ComboBox.Resources>
        <Style TargetType="ComboBox">
            <Style.Triggers>
                <Trigger Property="SelectedItem" Value="{x:Null}">
                    <Setter Property="SelectedIndex" Value="0"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </ComboBox.Resources>
  </ComboBox>