【问题标题】:Windows Phone 7 XAML -- getting a binding to work with the container of my objectWindows Phone 7 XAML - 获取绑定以使用我的对象的容器
【发布时间】:2011-04-25 03:49:52
【问题描述】:

我想要做的是将 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 class 与其他版本不同。

【问题讨论】:

    标签: xaml windows-phone-7 binding relativesource


    【解决方案1】:

    需要设置用户控件的DataContext。

    如果你添加这个:

    this.DataContext = this;
    

    进入用户控件的构造函数或 Loaded 事件,您可以这样做:

    Text="{Binding ButtonSymbol}"
    

    请注意,您还可以以声明方式绑定 XAML 的 DataSource,这只是一种简单的编程方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-30
      • 2013-06-08
      • 1970-01-01
      • 1970-01-01
      • 2011-06-20
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多