How to create a Dependency property on an existing control?

时光总嘲笑我的痴心妄想 提交于 2019-12-01 04:08:31

You can use attached properties for it.

Define your property 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);
        }
    }
}

Bind label content:


<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>

You cant add DependencyProperties to existing type. While you can use AttachedProperty, logic behind using it and deriving new type is completly different.

In your case I would recomend to derive new type. Mainly because your logic is bound with this type. This is basic behind inheritance and is not bound with Dependency properties.

In case of AttachedProperty you are only giving another object awerness of values in different object. Something like Grid.Row is giving Grid awerness of its child and how it should position it. Object where this property is set is not aware of anything.

Here is an example on an ovveride of the Run element:

using System;
using System.Windows;
using System.Windows.Documents;

namespace MyNameSpace.FlowDocumentBuilder
{
    public class ModifiedRun : Run
    {
        static DateRun()
        {
            TextProperty.OverrideMetadata(typeof(DateRun),new FrameworkPropertyMetadata(string.Empty,FrameworkPropertyMetadataOptions.Inherits,null,CoerceValue));
        }

        private static object CoerceValue(DependencyObject d, object basevalue)
        {
            return "AAAAAAAA";
        }
    }
}

An the corresponding XAML is:

<FlowDocument xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                      ColumnWidth="400"
                      FontSize="14"
                      FontFamily="Arial"
xmlns:local="clr-namespace:MyNameSpace.FlowDocumentBuilder;assembly=MyNameSpace.FlowDocumentBuilder"
>

<Paragraph><local:ModifiedRun Text="BBBBBBBBBB"/></Paragraph>

</FlowDocument>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!