0

我有一个应用程序级别的样式ComboBoxItem

<Style TargetType="{x:Type ComboBoxItem}" x:Key="DefaultComboBoxItemStyle">
    <!-- ... -->
    <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
    <!-- ... -->
</Style>

<Style TargetType="{x:Type ComboBoxItem}" BasedOn="{StaticResource DefaultComboBoxItemStyle}" />

这种风格在 99% 的情况下都适合我。但是,当绑定对象没有IsSelected属性时,有 1%。我想覆盖这个绑定(特别是完全清除它)。

我想,这将是可能的:

        <!-- somewhere in application code -->
        <ComboBox Margin="5" ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}">
            <ComboBox.ItemContainerStyle>
                <Style TargetType="ComboBoxItem" BasedOn="{StaticResource DefaultComboBoxItemStyle}">
                    <Setter Property="IsSelected" Value="False"/>
                </Style>
            </ComboBox.ItemContainerStyle>
        </ComboBox>

但它不起作用,仍然存在绑定错误。有什么方法可以在 XAML 中实现我想要的吗?

4

2 回答 2

1

您可以在其本地创建不同的默认样式,而不是ItemContainerStyle为非默认组合框设置:Resources

<Window.Resources>
    <Style TargetType="ComboBoxItem">
        <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
        ...
    </Style>
</Window.Resources>
...
<ComboBox ...>
    <ComboBox.Resources>
        <!-- local default style based on "global" default style -->
        <Style TargetType="ComboBoxItem"
               BasedOn="{StaticResource ResourceKey={x:Type ComboBoxItem}}">
            <Setter Property="IsSelected" Value="False"/>
        </Style>
    </ComboBox.Resources>
</ComboBox>
于 2013-06-24T14:42:09.640 回答
0

您可以在应用程序级样式中将回退值设置为 false。

<Style TargetType="{x:Type ComboBoxItem}" x:Key="DefaultComboBoxItemStyle">
    <!-- ... -->
    <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay, FallbackValue=False}" />
    <!-- ... -->
</Style>

编辑: 尝试结合优先绑定的后备值以避免绑定错误。

修改后的应用程序样式看起来像

<Style TargetType="{x:Type ComboBoxItem}" x:Key="DefaultComboBoxItemStyle">
    <!-- ... -->
    <Setter Property="IsSelected">
        <Setter.Value>
            <PriorityBinding FallbackValue="False">
                <Binding Path="IsSelected" Mode="TwoWay" />
            </PriorityBinding>
        </Setter.Value>
    </Setter>
</Style>
于 2013-06-24T15:09:45.633 回答