Attachment to attached property

I am trying to bind a Button ContentTemplate element to an attached property. I read all the answers to a question similar to “binding to attached property”, but I could not solve the problem.

Please note that the example presented here is a stunning version of my problem to avoid clogging the business code problem.

So, I have a static class with a nested 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 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>

This is pretty much the case. I would expect that in the middle of the "Attached" button. Instead, a crash occurs: The property path is invalid. The extender does not have an open property named AttachedText.

SetAttachedText GetAttachedText, SetAttachedText , . GetAttachedText , .

( App.xaml), .

- ? ,

+4
1

. Extender, DependencyObject.

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

. MSDN RegisterAttached:

ownerType - ,

+5

All Articles