可以继承依赖属性(请参见第十点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
还是存在更方便的方法?
比我想象的要容易,我必须用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>