【问题标题】:Binding Button IsEnabled to ComboBox Selection将按钮 IsEnabled 绑定到组合框选择
【发布时间】:2015-02-25 00:38:18
【问题描述】:

我知道这可以在转换器中完成,但我想禁用基于在 ComboBox 中选择的特定项目的按钮,仅使用 XAML。

下面的工作,使用 Visibility 属性。如果我尝试使用 IsEnabled 怎么会不起作用?有什么我想念的吗?如果是这样的话,如果有人能解释为什么,那就太好了。我应该总是使用转换器吗?

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

作品:

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

不起作用:

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

【问题讨论】:

  • XAML 中的可见性与布尔值不同。这就是为什么我们有转换器 bool -> 可见性和可见性 -> bool ;)
  • 使用 IValueConverter 并不丢人。像“我只会使用 XAML”这样的人为约束并不总是最好的主意。
  • @jan.h,我同意。如果 XAML 太复杂或不太可读,我通常会尝试使用 XAML,然后使用转换器。谢谢。

标签: c# wpf xaml


【解决方案1】:

我实际上不确定第一个是如何工作的。这取决于您为按钮上的属性设置的内容。通常,您需要样式中的默认设置器并删除按钮上本地设置的任何 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>

这取决于设置属性值的优先级。例如,在本地设置的属性值会覆盖样式设置器/触发器。 This article 用一些例子解释了依赖属性的优先级。

【讨论】:

  • 使用默认设置器使其工作。感谢您的解释。这篇文章也有很大帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-12
  • 2011-08-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多