【问题标题】:WPF: Clickable button in ItemTemplate of a ComboBoxItem with IsEnabled=falseWPF:IsEnabled = false 的 ComboBoxItem 的 ItemTemplate 中的可单击按钮
【发布时间】:2017-08-23 11:39:36
【问题描述】:

尝试设置 WPF ComboBox; 它的一些项目不应该是可选择的,所以我将IsEnabled 绑定到底层项目的某些属性。

同时,我需要定义一个ItemTemplate,其中包含例如一个按钮。 这个按钮需要是可点击的,即使该项目是不可选择的(点击按钮当然不应该选择该项目;它会触发一个执行一些后台操作的命令,这最终将使底层项目可选择)

但是,当ComboBoxItem.IsEnabled = false 时,似乎连按钮都自动被禁用了。

简单示例:

    <ComboBox ItemsSource="{Binding Items}">
        <ComboBox.ItemContainerStyle>
            <Style TargetType="{x:Type ComboBoxItem}">
                <Setter Property="IsEnabled" Value="{Binding CanSelectItem}"/>
            </Style>
        </ComboBox.ItemContainerStyle>

        <ComboBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Name}"/>

                    <!-- This button isn't clickable when ComboBoxItem.IsEnabled = false .. but it should be! -->
                    <Button Content="Click me" Command="{Binding SomeCmd}"/>
                </StackPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

有什么办法可以规避吗?例如,将某些项目设置为不可选择,但在 ItemTemplate 中定义一个按钮,无论如何都可以点击?

谢谢

【问题讨论】:

  • 将 ComboBoxItem 设置为禁用将禁用其所有内容。也许不是禁用,而是在合适的时候取消SelectionChanged 事件?

标签: c# wpf


【解决方案1】:

当您删除ComboBox.ItemContainerStyle 时,您可以设置DataTemplate 中每个元素的IsEnabled 属性

<ComboBox.ItemTemplate>
    <DataTemplate>
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding Name}"
                       IsEnabled="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.IsEnabled}"/>
            <Button Content="Click me" Command="{Binding SomeCmd}"/>
        </StackPanel>
    </DataTemplate>
</ComboBox.ItemTemplate>

组合框项目仍将启用,但 TextBlock 将被禁用。 绑定只是一个例子。取决于您的 IsEnabled 属性在哪里。在我的示例中,该属性位于您的WindowDataContext 的视图模型中。

【讨论】:

  • 这是否允许选择项目(不管TextBlock 的状态为禁用)?我现在无法测试,谢谢。
  • @非破坏性该死的,是的......好点。据我所知,没有其他方法可以启用该按钮;正如您在另一条评论中提到的那样。
  • 好吧,如果该事件建议可行,您的回答可能仍然有用。您仍然希望(或至少看起来)禁用文本。
  • @nonspoken 是的,这就是我没有删除答案的原因。也许它仍然可以满足提问者的要求。
  • 感谢你们!有(可能没用的)习惯,即尽可能避免在视图中使用代码隐藏,但在这种情况下,看到这似乎是最好的 - 或唯一的 - 方式,将采用您建议的想法。谢谢
【解决方案2】:

为了将来参考,根据这个答案找到了另一种方法:

WPF override IsEnabled from Parent

所以基本上创建了一个派生自按钮的类,它覆盖了默认的 IsEnabled 行为。

好处是这似乎完全符合我的要求,但它确实改变了 WPF 的一个漂亮的..默认行为,所以可能需要小心一点

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    相关资源
    最近更新 更多