簡體   English   中英

如何將文本綁定到我的自定義XAML控件?

[英]How to bind text to my custom XAML control?

我想將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); }
    }
}

你近了 綁定的問題在於,它將在數據上下文而不是控件上搜索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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM