如何将文本绑定到我的自定义XAML控件?

时间:2015-08-05 10:28:35

标签: c# xaml windows-phone dependency-properties

我想将DependencyProperty绑定到我的TextBox,我需要做的是创建一个控件,允许我在其属性“Letter”中写入文本并将其设置为模板中定义的TextBlock的文本。我之前从未这样做过,所以我不知道该怎么做。

这是.xaml:

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:My_App">

<Style TargetType="local:GameLetter" >
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:GameLetter">
                <Grid>
                    <Image Source="Assets/imgs/letter_key.png"/>
                    <Viewbox Margin="10,0">
                        <TextBlock x:Name="textBlock" FontFamily="Assets/fonts/avenirnext.ttf#Avenir Next" Text="{Binding Letter}" Foreground="Black" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                    </Viewbox>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

这是.cs:

 public sealed class GameLetter : Control
{
    public GameLetter()
    {
        this.DefaultStyleKey = typeof(GameLetter);
    }

    public static readonly DependencyProperty LetterProperty =
        DependencyProperty.Register("Letter", typeof(string), typeof(GameLetter), new PropertyMetadata(null));

    public string Letter
    {
        get { return (string)GetValue(LetterProperty); }
        set { SetValue(LetterProperty, value); }
    }
}

1 个答案:

答案 0 :(得分:1)

你很亲密。绑定的问题是它将搜索datacontext上的Letter属性,而不是您的控件。您可以使用TemplateBinding

来解决这个问题
<Style TargetType="local:GameLetter" >
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:GameLetter">
                <Grid>
                    <Image Source="Assets/imgs/letter_key.png"/>
                    <Viewbox Margin="10,0">
                        <TextBlock x:Name="textBlock" FontFamily="Assets/fonts/avenirnext.ttf#Avenir Next" Text="{TemplateBinding Letter}" Foreground="Black" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                    </Viewbox>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>