[英]Binding to a depencency property doesn't work
I derived ImageButton from Button class. 我从Button类派生了ImageButton。 I want to be able to set text on it using custom property. 我希望能够使用自定义属性在其上设置文本。
ImageButton XAML 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 code behind 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();
}
}
Client code: 客户代码:
<local:ImageButton Margin="114,15.879,96,15.878" Grid.Row="2" ButtonText="test"/>
No text is being shown on the button. 按钮上没有显示任何文字。 For some reason the binding doesn't seem to be taking place. 出于某种原因,似乎没有发生绑定。 What am I doing wrong? 我究竟做错了什么?
You don't have a DataContext
set, so the data binding doesn't know which source object it should bind to. 您没有DataContext
集,因此数据绑定不知道它应绑定到哪个源对象。
I find that the easiest way to resolve this is to give your outer control a name, and reference it using ElementName
in your binding: 我发现解决此问题的最简单方法是为外部控件指定名称,并在绑定中使用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>
Change this 改变这个
<TextBlock Text="{Binding Path = ImageButton.ButtonText}"
to 至
<TextBlock Text="{Binding Path = ButtonText}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.