c# - 绑定(bind)到附加属性

标签 c# wpf attached-properties

我正在尝试从 Button 的 ContentTemplate 绑定(bind)到附加属性。我阅读了所有类似于“绑定(bind)到附加属性”的问题的答案,但我没有运气解决这个问题。

请注意,此处提供的示例是我的问题的简化版本,以避免将问题与业务代码混为一谈。

所以,我确实有带有附加属性的静态类:

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);
    }

  }
}

和一个窗口:

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

差不多就这些了。我希望在按钮中间看到“已附加”。 相反,它崩溃了:属性路径无效。 “Extender”没有名为“AttachedText”的公共(public)属性。

我已经在 SetAttachedText 和 GetAttachedText 上设置了断点,并且 SetAttachedText 被执行,所以将它附加到按钮工作。 GetAttachedText 永远不会执行,因此它在解析时找不到属性。

我的问题实际上更复杂(我试图从 App.xaml 中的 Style 内部进行绑定(bind))但让我们从简单的开始。

我错过了什么吗? 谢谢,

最佳答案

您的属性(property)登记有误。 ownerTypeExtender,而不是 DependencyObject

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

请参阅 RegisterAttached 的 MSDN 文档:

ownerType - The owner type that is registering the dependency property

关于c# - 绑定(bind)到附加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19769263/

相关文章:

c# - 我如何将一个类(派生自通用 "base"类)转换为该通用 "base"类

c# - 如何从不同的组件扩展模型?

.net - WPF 风格行为异常

wpf - 类型委托(delegate)的 DependencyProperty

c# - 无法找到请求的 .Net Framework 数据提供程序。它可能没有安装。 vs 2010 和 sql server 2008 express

c# - 为什么在采用对象初始化器时使用 (int?) null?

c# - WPF从按钮传递按钮内容?

.net - 如何在 HierarchicalDataTemplate 的 DataType 属性中引用泛型类型?

wpf - 将附加的依赖项属性值传播到模板

wpf - 公共(public)与私有(private)附加属性