如何将TextBlock绑定到自制的FrameworkElement属性?

时间:2017-12-11 22:02:19

标签: c# wpf xaml

我有一个' GameControl:FrameworkElement'。我在xaml中有这样的:

<local:GameControl x:Name="control"/>

此GameControl有一个属于自己的类:

public Gem selectedGem {get; set;}

现在,我想将这个Gem的信息写入TextBlock,以便玩家看到它的属性。

如何将自己的FrameworkElement属性绑定到MainWindow的元素?

-

完整的xaml:

<Window x:Class="GemTowerDefense.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:GemTowerDefense"
    mc:Ignorable="d"
    Title="Gem Tower Defense" Height="670" Width="800"
    ResizeMode="NoResize">
<Grid>
    <Border Background="Gray" Height="600" Width="600" Margin="3,26,189,3">
        <local:GameControl x:Name="control"/>
    </Border>

    <Border Background="LightSlateGray" HorizontalAlignment="Left" VerticalAlignment="Top" Height="285" Margin="608,181,0,0" Width="170">
        <TextBlock x:Name="tbInfo" Text="Gem information">
        </TextBlock>
    </Border>
</Grid>
</Window>

(而不是Text = Gem信息,我希望绑定到控件的selectedGem,或者它的一个字符串类型属性)

1 个答案:

答案 0 :(得分:1)

您将属性设为dependency property,并且在将该属性绑定到TextBlock.Text时,请使用转换器。搜索Stackoverflow以找到关于这两个主题的十亿个示例。绑定看起来像这样:

Text="{Binding ElementName=control, Mode=OneWay, Path=selectedGem, Converter={local:ExampleConverter}}"

我发现在代码隐藏中创建转换器最简单:

public class ExampleConverter : MarkupExtension, IValueConverter
{
    public ExampleConverter()
    {

    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }

    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if(value != null && value is Gem)
            return (value as Gem).GemAsText();
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value;
    }
    #endregion
}