简体   繁体   English

绑定按钮IsEnabled到ComboBox选择

[英]Binding Button IsEnabled to ComboBox Selection

I know this can be done in a converter, but I'd like to disable a button based on a particular item selected in a ComboBox, using only XAML. 我知道这可以在转换器中完成,但我想基于ComboBox中选择的特定项目禁用一个按钮,仅使用XAML。

The following below works, using the Visibility property. 以下内容使用Visibility属性。 How come if I try to use IsEnabled it does not work? 为什么我尝试使用IsEnabled它不起作用? Is there something I'm missing? 有什么我想念的吗? If that's the way it is, if someone could explain why, that would be great. 如果是这样的话,如果有人可以解释原因,那就太好了。 Should I just always use converters? 我应该只使用转换器吗?

<ComboBox Name="WidthTypeComboBox" 
    ItemsSource="{Binding Source={StaticResource WidthType}}" 
    SelectedItem="{Binding WidthTypeSelected}" />

Works: 作品:

<Button Content="Map Channels" Command="{Binding ShowChannelAction}">
    <Button.Style>
        <Style TargetType="Button">
            <Style.Triggers>
                <DataTrigger Binding="{Binding SelectedIndex, 
                    ElementName=WidthTypeComboBox}" Value="0">
                    <Setter Property="Visibility" Value="Visible" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

Does not work: 不起作用:

<Button Content="Map Channels" Command="{Binding ShowChannelAction}">
    <Button.Style>
        <Style TargetType="Button">
            <Style.Triggers>
                <DataTrigger Binding="{Binding SelectedIndex, 
                    ElementName=WidthTypeComboBox}" Value="0">
                    <Setter Property="IsEnabled" Value="True" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

I'm actually not sure how the first one is working. 我实际上不确定第一个是如何工作的。 It depends on what you've set for the properties on your button. 这取决于您为按钮上的属性设置的内容。 Usually you need a default setter in the style and to remove any IsEnabled value set locally on the button: 通常,您需要样式中的默认setter并删除按钮上本地设置的任何IsEnabled值:

<Style TargetType="Button">
    <Setter Property="IsEnabled" Value="False" />
    <Style.Triggers>
        <DataTrigger Binding="{Binding SelectedIndex, 
            ElementName=WidthTypeComboBox}" Value="0">
            <Setter Property="IsEnabled" Value="True" />
        </DataTrigger>
    </Style.Triggers>
</Style>

It comes down to the precedence of where the property value is set. 它归结为属性值设置的优先级。 For example, property values set locally override style setter/triggers. 例如,在本地设置的属性值覆盖样式setter / triggers。 This article explains dependency property precendence with some examples. 本文通过一些示例解释依赖属性优先级。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM