【问题标题】:How to bind text to my custom XAML control?如何将文本绑定到我的自定义 XAML 控件?
【发布时间】:2015-08-05 10:28:35
【问题描述】:

我想将一个 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); }
    }
}

【问题讨论】:

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


    【解决方案1】:

    你已经接近了。您的绑定的问题是它会在您的数据上下文中搜索 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>
    

    【讨论】:

      猜你喜欢
      • 2013-03-29
      • 1970-01-01
      • 1970-01-01
      • 2016-04-23
      • 2010-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多