Problem reading AttachedProperty in ControlTemplate

早过忘川 提交于 2019-12-11 06:51:57

问题


This is my attached property:

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));
}

This is my ControlTemplate:

EDIT this will work fine:

<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>

My problem? Text2 renders properly in the Desginer, not at runtime.


回答1:


You set the value on the button, and it is attached, hence:

{Binding RelativeSource={RelativeSource AncestorType=Button},
         Path=(local:MyButtonThing.Text2)}



回答2:


You are binding to the DataContext of TextBox, which doesn't have a Text2 property

Use this instead:

<TextBlock Text="{Binding RelativeSource={RelativeSource Self},
                   Path=local:MyButtonThing.Text2}" />

It sets the TextBox's DataContext to the TextBox Control, not the TextBox's DataContext



来源:https://stackoverflow.com/questions/7014924/problem-reading-attachedproperty-in-controltemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!