我需要我的控件从 Grid 类型的 Ancestor 继承 UIElement.IsEnabledProperty(可选 Window 或任何其他我可以包装我的网格的元素)
CS:下面我重写了 UIElement.IsEnabledProperty 的元数据,并使用 Change 和 Coerce 委托(delegate)对其进行设置。
static PipeControl()
{
PipeControl.IsEnabledProperty.OverrideMetadata(typeof(PipeControl), new FrameworkPropertyMetadata(false, OnIsEnabledPropertyChanged, OnIsEnabledPropertyCoerce));
}
private static void OnIsEnabledPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var isEnabled = (bool)e.NewValue;
}
private static object OnIsEnabledPropertyCoerce(DependencyObject d, object baseValue)
{
var valueSource = DependencyPropertyHelper.GetValueSource(d, PipeControl.IsEnabledProperty);
var pipeContorl = d as PipeControl;
if (pipeContorl == null) return baseValue;
return (bool)baseValue && pipeContorl.IsMyPipe;
}
XAML:
<Grid IsEnabled="{Binding IsMyCondition , Mode=OneWay}">
<game:PipeControl Grid.Row="2" />
<game:PipeControl Grid.Row="2" Grid.Column="1" />
</Grid>
每次 IsMyCondition 更改时,在每个 PipeContorl 中调用 OnIsEnabledPropertyCoerce, 永远不会调用 OnIsEnabledPropertyChanged , OnIsEnabledProerty Coerce 中的 ValueSource 是“Default”(显示 Coerce 始终获得默认的 false 值)。
我一定是错过了一些我需要使用继承的方式, 我希望值(value)来源是“继承的” 和要调用的 OnIsEnabledPropertyChanged。
最佳答案
UIElement 有一个虚拟属性 IsEnabledCore 应该(?)用于强制 IsEnabled 属性。这就是 Button 或 MenuItem 如何根据它们的 CanExecute 属性强制 IsEnabled 属性。 在您的自定义控件中,您可以将该属性覆盖为:
protected override bool IsEnabledCore
{
get
{
return ( base.IsEnabledCore && IsMyPipe );
}
}
重要的是当 IsEnabled 所依赖的任何属性(例如 IsMyPipe)发生变化时调用 CoerceValue。
因此自定义控件实现将是:
static PipeControl()
{
DefaultStyleKeyProperty.OverrideMetadata( typeof( PipeControl ), new FrameworkPropertyMetadata( typeof( PipeControl ) ) );
}
public bool IsMyPipe
{
get { return ( bool )GetValue( IsMyPipeProperty ); }
set { SetValue( IsMyPipeProperty, value ); }
}
public static readonly DependencyProperty IsMyPipeProperty =
DependencyProperty.Register(
"IsMyPipe",
typeof( bool ),
typeof( UIElement ),
new PropertyMetadata(
true,
new PropertyChangedCallback( OnIsMyPipeChanged ) ) );
private static void OnIsMyPipeChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
d.CoerceValue( UIElement.IsEnabledProperty );
}
希望这对您有所帮助,欢迎对解决方案提出任何意见。
关于wpf - 依赖属性继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15918293/