这是我附属的财产:
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:
编辑这样可以正常使用:
<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中正确呈现,而不是在运行时。
答案 0 :(得分:1)
您在按钮上设置了值,并且已附加,因此:
{Binding RelativeSource={RelativeSource AncestorType=Button},
Path=(local:MyButtonThing.Text2)}
答案 1 :(得分:0)
您绑定到DataContext
的{{1}},TextBox
没有Text2
属性
请改用:
<TextBlock Text="{Binding RelativeSource={RelativeSource Self},
Path=local:MyButtonThing.Text2}" />
它将TextBox的DataContext
设置为TextBox控件,而不是TextBox的DataContext