Windows Phone 7 XAML — getting a binding to work with the container of my object

家住魔仙堡 提交于 2019-12-11 07:35:10

问题


What I want to do is bind the text of a TextBlock to my custom ButtonSymbol property of the UserControl.

Here is the XAML for the UserControl. The Binding part for the TextBlock needs to be filled in.

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

And here is the CodeBehind:

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.
        }
    }
}

Note that this is WP7 with Silverlight, and the RelativeSource class is not the same as in other versions.


回答1:


You need to set the DataContext of the user control.

If you add this:

this.DataContext = this;

into the constructor or Loaded event of the user control you can then do this:

Text="{Binding ButtonSymbol}"

Note that you can also declaratively bind the DataSource of the XAML, this is just an easy programmatic way to do it.



来源:https://stackoverflow.com/questions/5774995/windows-phone-7-xaml-getting-a-binding-to-work-with-the-container-of-my-objec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!