我正在尝试从 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)登记有误。 ownerType 是 Extender
,而不是 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/