从wpf

时间:2016-09-06 15:56:36

标签: wpf mvvm combobox

我在每个数据网格行中创建了一个组合框。以下代码用于创建组合框:

<ComboBox Width="166"
          ItemTemplate="{StaticResource GridBinding}"
          SelectedItem="{Binding Path=Car, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, IsAsync=True}"
          SelectedValue="{Binding Path=Car, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, IsAsync=True}">
    <ComboBox.GroupStyle>
        <GroupStyle HeaderTemplate="{StaticResource GroupHeader}" />
    </ComboBox.GroupStyle>
    <ComboBox.Style>
        <Style TargetType="ComboBox">
            <Setter Property="ItemsSource" Value="{Binding Path=Cars}" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=IsSelected, RelativeSource={RelativeSource AncestorType=DataGridCell}}" Value="True">
                    <Setter Property="ItemsSource" Value="{Binding Path=DataContext.GroupedCars, RelativeSource={RelativeSource AncestorType=DataGrid}}" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ComboBox.Style>
</ComboBox>

&#34; Car&#34;绑定的属性&#34; SelectedItem&#34;在组合框中是一个对象&#34; Car&#34;持有一些属性,如id,name等。

我面临的问题是当我更新&#34; Car&#34;财产和电话&#34; NotifyPropertyChanged&#34;在它的setter中,然后是&#34; SelectedItem&#34;的值。在组合框中变为空白/空。

请建议。

1 个答案:

答案 0 :(得分:1)

在Collection中找不到SelectedItem(更新ItemSource时)并将其设置为null。

我已经简化了您的XAML以演示

<ComboBox ItemsSource="{Binding Cars}"
          SelectedItem="{Binding Car}">
    <ComboBox.Style>
        <Style TargetType="ComboBox">
            <Style.Triggers>
                <Trigger Property="SelectedItem" Value="{x:Null}">
                    <Setter Property="SelectedIndex" Value="0" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ComboBox.Style>
</ComboBox>

现在更新时会选择第一个项目。