3

假设我有一些控件已被禁用。它包含一堆元素,但我希望其中一个子元素保持启用状态。

像这样的东西:

<ContentControl IsEnabled="False">
    <Border>
        <Button Content="Button" IsEnabled="True"/>
    </Border>
</ContentControl>

所以在本例中,Button 的 IsEnabled="True" 设置被其父级覆盖。有没有办法阻止这种情况发生?

这似乎是一件奇怪的事情,但我有一种情况,当一个控件被禁用并且用户将鼠标放在它上面时,我仍然希望触发一个事件。

我在 WPF Unleashed 中读到将某些内容包装在 Frame 控件中,“..将内容与 UI 的其余部分隔离 [和] 通常会在到达 Frame 时停止沿元素树继承的属性”,但包装了 Button在上面的示例中的 Frame 中不起作用。

我在这里走错了吗?

4

2 回答 2

4

这不是继承,而是组合

包含控件被禁用,因此其所有包含的控件都被禁用

启用所需的容器和控件,并禁用其他控件

于 2010-03-15T19:19:12.520 回答
4

如果您可以继承按钮(或您需要的任何控件),则可以替换 CoerceValue 以避免这种行为(实际上,我认为 IsEnabled 应该像 IsChecked 一样工作,是一个布尔值?,其中 null 表示使用父值,任何应保留特定值...但由于这不是行为,因此使用此解决方案将解决问题):

public sealed class InheritedButton:
  Button
{
  static InheritedButton()
  {
    InheritedButton.IsEnabledProperty.OverrideMetadata
    (
      typeof(InheritedButton),
      new FrameworkPropertyMetadata
      (
        true,
        null,
        _CoerceIsEnabled
      )
    );
  }
  private static object _CoerceIsEnabled(DependencyObject source, object value)
  {
    return value;
  }
}
于 2013-05-29T14:03:16.517 回答