Binding to attached property

夙愿已清 提交于 2019-12-20 01:09:37

问题


I'm trying to bind from Button's ContentTemplate to attached property. I read all the answers for question similar to "binding to attached property" but I had no luck resolving the problem.

Please note that example presented here is a dumbed down version of my problem to avoid cluttering the problem with business code.

So, I do have static class with attached property:

using System.Windows;

namespace AttachedPropertyTest
{
  public static class Extender
  {
    public static readonly DependencyProperty AttachedTextProperty = 
      DependencyProperty.RegisterAttached(
        "AttachedText",
        typeof(string),
        typeof(DependencyObject),
        new PropertyMetadata(string.Empty));

    public static void SetAttachedText(DependencyObject obj, string value)
    {
      obj.SetValue(AttachedTextProperty, value);
    }

    public static string GetAttachedText(DependencyObject obj)
    {
      return (string)obj.GetValue(AttachedTextProperty);
    }

  }
}

and a window:

<Window x:Class="AttachedPropertyTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:AttachedPropertyTest"
        Title="MainWindow" Height="350" Width="525">
  <Grid>
    <Button local:Extender.AttachedText="Attached">
      <TextBlock 
        Text="{Binding 
          RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button},
          Path=(local:Extender.AttachedText)}"/>
    </Button>
  </Grid>
</Window>

That's pretty much it. I would expect t see "Attached" in the middle of the button. Instead it crashes with: Property path is not valid. 'Extender' does not have a public property named 'AttachedText'.

I've set breakpoints on SetAttachedText and GetAttachedText, and SetAttachedText is executed, so attaching it to button works. GetAttachedText is never executed though, so it does not find property when resolving.

My problem is actually more complicated (I'm trying to do binding from inside of Style in App.xaml) but let's start with the simple one.

Did I miss something? Thanks,


回答1:


Your attached property registration is wrong. The ownerType is Extender, not DependencyObject.

public static readonly DependencyProperty AttachedTextProperty = 
    DependencyProperty.RegisterAttached(
        "AttachedText",
        typeof(string),
        typeof(Extender), // here
        new PropertyMetadata(string.Empty));

See the MSDN documentation for RegisterAttached:

ownerType - The owner type that is registering the dependency property



来源:https://stackoverflow.com/questions/19769263/binding-to-attached-property

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