本文介绍了在ControlTemplate中读取AttachedProperty时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的附属财产:
public class MyButtonThing
{
public static string GetText2(DependencyObject obj)
{
return (string)obj.GetValue(Text2Property);
}
public static void SetText2(DependencyObject obj, string value)
{
obj.SetValue(Text2Property, value);
}
public static readonly DependencyProperty Text2Property =
DependencyProperty.RegisterAttached("Text2",
typeof(string), typeof(System.Windows.Controls.Button));
}
这是我的ControlTemplate:
This is my ControlTemplate:
编辑,它将正常工作:
<Window.Resources>
<ControlTemplate TargetType="{x:Type Button}"
x:Key="MyButtonTemplate">
<Border>
<DockPanel LastChildFill="True">
<TextBlock Text="{TemplateBinding Content}"
DockPanel.Dock="Top"/>
<TextBlock Text={Binding RelativeSource={RelativeSource
AncestorType=Button},
Path=(local:MyButtonThing.Text2)}" />
</DockPanel>
</Border>
</ControlTemplate>
</Window.Resources>
<Button Template="{StaticResource MyButtonTemplate}"
local:MyButtonThing.Text2="Where's Waldo"
>Hello World</Button>
我的问题吗? Text2可以在Desginer中正确呈现,而不是在运行时呈现.
My problem? Text2 renders properly in the Desginer, not at runtime.
推荐答案
您在按钮上设置了值,该值即被附加,因此:
You set the value on the button, and it is attached, hence:
{Binding RelativeSource={RelativeSource AncestorType=Button},
Path=(local:MyButtonThing.Text2)}
这篇关于在ControlTemplate中读取AttachedProperty时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!