1

私がしたいことは、TextBlock のテキストを UserControl のカスタム ButtonSymbol プロパティにバインドすることです。

UserControl の XAML は次のとおりです。TextBlock の Binding 部分に入力する必要があります。

<UserControl
    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"
    mc:Ignorable="d"
    x:Class="Calculator.CalculatorButton"
    d:DesignWidth="120" d:DesignHeight="80">

    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Image Source="buttonb@2x.png" Stretch="Fill"/>
        <Button x:Name="InvisibleButton" Content="{Binding ButtonSymbol}" Margin="0,0,0,0" d:LayoutOverrides="Width, Height" BorderThickness="1" Click="InvisibleButton_Click"/>
    <TextBlock HorizontalAlignment="Center" Margin="0,0,0,0" TextWrapping="Wrap" 
               Text="{Binding ????????}" 
               VerticalAlignment="Top"/>
    </Grid>
</UserControl>

コードビハインドは次のとおりです。

namespace Calculator
{
    public partial class CalculatorButton : UserControl
    {
        public string ButtonSymbol {get; set;}

        public CalculatorButton()
        {
            // Required to initialize variables
            InitializeComponent();
        }

        private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // TODO: Add event handler implementation here.
        }

        private void InvisibleButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Debug.WriteLine(@"click");
            Debug.WriteLine(ButtonSymbol);
            // TODO: Add event handler implementation here.
        }
    }
}

これは Silverlight を使用した WP7 であり、RelativeSource クラスは他のバージョンと同じではないことに注意してください。

4

1 に答える 1

3

ユーザー コントロールの DataContext を設定する必要があります。

これを追加すると:

this.DataContext = this;

ユーザーコントロールのコンストラクターまたは Loaded イベントに追加すると、次のことができます。

Text="{Binding ButtonSymbol}"

XAML の DataSource を宣言的にバインドすることもできることに注意してください。これは、プログラムによる簡単な方法です。

于 2011-04-25T03:59:09.230 に答える