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