绑定到依赖项属性不起作用

时间:2012-06-21 20:42:02

标签: c# wpf xaml binding dependency-properties

我从Button类派生了ImageButton。我希望能够使用自定义属性在其上设置文本。

ImageButton XAML

<Button x:Class="MyProject.ImageButton"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="50" Width="75" Template="{DynamicResource BlueButton}">
    <StackPanel>
        <TextBlock Text="{Binding Path = ImageButton.ButtonText}" TextWrapping="Wrap" Foreground="White"/>
    </StackPanel>
</Button>

背后的ImageButton代码

    public partial class ImageButton : Button
    { 
        public string ButtonText
        {
            get { return (string)GetValue(ButtonTextProperty); }
            set { SetValue(ButtonTextProperty, value); }
        }

        public static readonly DependencyProperty ButtonTextProperty =
            DependencyProperty.Register("ButtonText", typeof(string), typeof(ImageButton), new UIPropertyMetadata(string.Empty));

        public ImageButton()
        {
            InitializeComponent();
        }
    }

客户代码:

<local:ImageButton Margin="114,15.879,96,15.878" Grid.Row="2" ButtonText="test"/>

按钮上没有显示任何文字。出于某种原因,似乎没有发生绑定。我做错了什么?

2 个答案:

答案 0 :(得分:3)

您没有设置DataContext,因此数据绑定不知道它应绑定到哪个源对象。

我发现解决此问题的最简单方法是为外部控件命名,并在绑定中使用ElementName引用它:

<Button x:Class="MyProject.ImageButton"
        x:Name="myImageButton"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Height="50" Width="75" Template="{DynamicResource BlueButton}">
    <StackPanel>
        <TextBlock Text="{Binding ElementName=myImageButton, Path=ButtonText}" 
                   TextWrapping="Wrap" Foreground="White"/>
    </StackPanel>
</Button>

答案 1 :(得分:0)

更改此

 <TextBlock Text="{Binding Path = ImageButton.ButtonText}" 

   <TextBlock Text="{Binding Path = ButtonText}"