且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

以编程方式绑定 WPF 中的附加属性

更新时间:2022-10-20 22:38:18

你可以像这样直接从附加的属性创建一个 PropertyPath:

var 绑定 = 新绑定{Path = new PropertyPath(CueBanner.PaddingProperty),//这里来源 = 装饰元素};

I'm using Jason Kemp's cool CueBanner class for "watermarking" text boxes in WPF:

<TextBox 
    hpext:CueBanner.Content="Find Text"
    hpext:CueBanner.Padding="2,6,0,0"
    />

Jason's code creates a ContentPresenter programmatically, sets its content to the CueBanner.Content, adds the ContentPresenter to an Adorner subclass, and displays it when appropriate.

His code infers the ContentPresenter from padding and margin of the adorned control, but I added hpext:CueBanner.Padding instead so I could set it explicitly to a value I like better.

contentPresenter.Margin = CueBanner.GetPadding(adornedElement);

So far so good.

Here's the trouble: It works but I'd like to bind it instead.

var binding = new Binding("hpext:CueBanner.Padding") { Source = adornedElement };

BindingOperations.SetBinding(contentPresenter, ContentPresenter.MarginProperty, binding);

But what do I use for a path for the source property? "hpext:CueBanner.Padding" doesn't work and it shouldn't work; that namespace doesn't exist there. No joy with "CueBanner.Padding" and "(CueBanner.Padding)". "MyProject.Extensions.CueBanner.Padding" doesn't work either and I can't see why it ought to.

I can't see anything that looks helpful in PropertyPath, but when I read that my mind starts to go a little blank.

I should be just doing this in XAML, shouldn't I?

You may directly create a PropertyPath from the attached property like this:

var binding = new Binding
{
    Path = new PropertyPath(CueBanner.PaddingProperty), // here
    Source = adornedElement
};