4
我试图从Button的ContentTemplate绑定到附加属性。我阅读所有类似于“绑定到附加属性”的问题的答案,但我没有解决问题的运气。绑定到附加属性
请注意,此处介绍的示例是我的问题的简化版本,以避免混淆业务代码问题。
所以,我确实有附加属性的静态类:
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'的公共属性。
我对SetAttachedText和GetAttachedText设置断点,SetAttachedText 是执行,所以其附加到按钮的作品。 GetAttachedText从不执行,所以在解析时它不会找到属性。我的问题其实更复杂(我试图从App.xaml中的Style内部进行绑定),但让我们从简单的一个开始吧。
我错过了什么吗? 谢谢,
烨。我认为(错误地)ownerType是属性可以附加到的类型。谢谢。 –