Search code examples
c#xamlwindows-phonedependency-properties

How to bind text to my custom XAML control?


I want to bind a DependencyProperty to my TextBox, what I need to do is to create a control that allows me to write a text in its property "Letter" and sets it as the text of the TextBlock defined in the template. I've never done this before so I'm not sure of how to do it.

Here's the .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>

And here's the .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); }
    }
}

Solution

  • You're close. The problem with your binding is that it'll search the Letter property on your datacontext, not on your control. You can fix that by using a 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>