2011-04-25 56 views
1

我想要做的是將TextBlock的文本綁定到UserControl的自定義ButtonSymbol屬性。Windows Phone 7 XAML - 獲取綁定以使用我的對象容器

這是UserControl的XAML。需要爲TextBlock的結合部要填寫

<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="[email protected]" 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. 
     } 
    } 
} 

注意,這是WP7使用Silverlight,以及RelativeSource class是不一樣的其他版本。

回答

3

您需要設置用戶控件的DataContext。

如果你補充一點:到用戶控件的構造函數或Loaded事件

this.DataContext = this; 

然後你可以這樣做:

Text="{Binding ButtonSymbol}" 

請注意,您也可以聲明綁定的數據源XAML,這只是一個簡單的編程方式。