如何在现有控件上创建Dependency属性?

Hou*_*man 8 .net wpf dependency-properties

我已经阅读了几天的依赖属性,并了解它们如何检索值而不是像在CLR属性中那样设置/获取它们.如果我错了,请随意纠正我.

根据我的理解,从DependencyObject派生的所有WPF控件(如TextBlock,Button等)也将包含用于存储其值的依赖项属性,而不是使用CLR属性.这具有在使用动画时覆盖本地值的优点,或者如果根本没有设置本地值则继承值.

我现在正试图想出一些样本来创建和使用我自己的dp.

1)是否可以在现有的WPF控件上创建自己的依赖项属性?假设我想在WPF Textblock类上使用integer类型的依赖项属性?或者我是否必须创建一个派生自TextBlockBase的新类,以便在那里创建我的依赖属性?

2)在任何一种情况下,假设我在WPF文本块类上创建了一个依赖属性.现在我想通过将label的内容绑定到TextBlock的依赖属性来利用它.因此标签将始终显示TextBlock的dp的实际值,无论它是继承还是本地设置.

希望有人可以帮我解决这两个例子......非常感谢,Kave

Ser*_*sov 7

您可以使用附加属性.

定义你的属性MyInt:


namespace WpfApplication5
{
    public class MyProperties
    {
        public static readonly System.Windows.DependencyProperty MyIntProperty;

        static MyProperties()
        {
            MyIntProperty = System.Windows.DependencyProperty.RegisterAttached(
                "MyInt", typeof(int), typeof(MyProperties));
        }

        public static void SetMyInt(System.Windows.UIElement element, int value)
        {
            element.SetValue(MyIntProperty, value);
        }

        public static int GetMyInt(System.Windows.UIElement element)
        {
            return (int)element.GetValue(MyIntProperty);
        }
    }
}

Run Code Online (Sandbox Code Playgroud)

绑定标签内容:


<Window x:Class="WpfApplication5.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication5"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <Label Margin="98,115,51,119" Content="{Binding Path=(local:MyProperties.MyInt), RelativeSource={x:Static RelativeSource.Self}}" local:MyProperties.MyInt="42"/>
    </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)