首页 > 解决方案 > 依赖属性 - 从另一个属性继承?

问题描述

我的 WPF 中有一个自定义依赖属性,UserControl名为CustomForeground.

如果UserControl.ForeGround没有在CustomForeground.

我正在使用以下代码,它可以工作,但肯定感觉有点hacky。

谁能确认确认是否有实现此依赖属性的“正确”方式?

public SolidColorBrush CustomForeground
{
      get { return (SolidColorBrush)(GetValue(CustomForegroundProperty) ?? GetValue(ForegroundProperty)); }
      set { SetValue(CustomForegroundProperty, value); }
}

注意 - 我省略了声明,DependencyProperty因为它只是样板文件。

标签: c#wpfdependency-properties

解决方案


您可以使用为 CustomForeground 属性设置一个绑定到其 Foreground 属性的 Setter 将 Style 添加到您的 UserControl。

除非 CustomForeground 属性值被另一个 Binding 或本地值或动画等替换,否则将使用 Binding。

<UserControl ...>
    <UserControl.Style>
        <Style>
            <Setter
                Property="local:MyUserControl.CustomForeground"
                Value="{Binding Foreground, RelativeSource={RelativeSource Self}}"/>
        </Style>
    </UserControl.Style>
    ...
</UserControl>

推荐阅读