如何清除应用程序级样式中定义的绑定?

时间:2013-06-24 13:55:35

标签: c# wpf xaml

我有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中实现我想要的东西?

2 个答案:

答案 0 :(得分:1)

您可以在其本地ItemContainerStyle中创建不同的默认样式,而不是为非默认的ComboBox设置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>

答案 1 :(得分:0)

您可以在应用程序级别样式中将fallback value设置为false。

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

修改 尝试将FallBack值与Priority Binding结合使用以避免绑定错误。

修改后的应用程序样式将如下所示

<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>