如何使IsEnabled可继承

问题描述 投票:1回答:1

可以继承依赖属性(请参见第十点here),这是一个不错的功能:

<Grid TextBlock.FontSize="100">
... any TextBlock inside will inherit this value
</Grid>

为了使附加属性TextBlock成为可能have to useAddOwner()TextElement.FontSize。设置附加属性(TextBlock或TextElement)都可以。

我想实现以下目标:

<Grid local:MyControl.IsEnabled="False">
... somewhere inside MyControl will get disabled
</Grid>

而且我不确定如何实现它,因为IsEnabled没有附加属性(意味着我不能使用上述语法),也不想禁用all UIElements

正确的方法是什么?是要创建新的附加属性并在其回调中更改IsEnabled还是存在更方便的方法?

c# wpf inheritance dependency-properties
1个回答
0
投票

比我想象的要容易,我必须用MyControl将附加属性添加到FrameworkPropertyMetadataOptions.Inherits,其余的由WPF完成。

MyControl应该看起来像这样:

public class MyControl : Grid
{
    public static bool GetDisabled(DependencyObject obj) => (bool)obj.GetValue(DisabledProperty);
    public static void SetDisabled(DependencyObject obj, bool value) => obj.SetValue(DisabledProperty, value);

    public static readonly DependencyProperty DisabledProperty =
        DependencyProperty.RegisterAttached("Disabled", typeof(bool), typeof(MyControl), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.Inherits, (d, e) =>
        {
            if (d is MyControl control)
                control.IsEnabled = !(bool)e.NewValue;
        }));
}

回调多次被调用,因此我必须直接检查何时在MyControl上调用它,并在此简单地设置IsEnabled。它适用于所有情况:添加子项,更改父项的值等。

用法与我想要的完全一样:

<Grid local:MyControl.Disabled="True">
    <local:MyControl/>
</Grid>
© www.soinside.com 2019 - 2024. All rights reserved.