我将尝试从按钮的ContentTemplate中绑定到附加属性。我阅读了所有与“绑定到附加属性”类似的问题的答案,但是我没有运气解决这个问题。
请注意,这里呈现的示例是我问题的简化版本,以避免使用业务代码混淆问题。
因此,我确实具有带有附加属性的静态类:
这就是全部内容了。我期望在按钮中间看到“Attached”字样。 但实际上它会崩溃,显示错误信息:属性路径无效。“Extender”没有名为“AttachedText”的公共属性。 我已经在SetAttachedText和GetAttachedText上设置了断点,因此将其附加到按钮上是有效的。然而,GetAttachedText从未执行过,因此在解析时找不到该属性。
我的问题实际上更复杂(我正在尝试在App.xaml的Style中进行绑定),但让我们从简单的问题开始。
我有什么遗漏吗? 谢谢。
请注意,这里呈现的示例是我问题的简化版本,以避免使用业务代码混淆问题。
因此,我确实具有带有附加属性的静态类:
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>
这就是全部内容了。我期望在按钮中间看到“Attached”字样。 但实际上它会崩溃,显示错误信息:属性路径无效。“Extender”没有名为“AttachedText”的公共属性。 我已经在SetAttachedText和GetAttachedText上设置了断点,因此将其附加到按钮上是有效的。然而,GetAttachedText从未执行过,因此在解析时找不到该属性。
我的问题实际上更复杂(我正在尝试在App.xaml的Style中进行绑定),但让我们从简单的问题开始。
我有什么遗漏吗? 谢谢。