我创建了一个UserControl,其中包含一个名为 CustomLabel 的依赖项属性,类型为String。
控件包含Label,它应显示 CustomLabel 属性的值。
我可以使用 OnLabelPropertyChanged 事件处理程序在代码中执行此操作:
public class MyControl : UserControl
{
public static readonly DependencyProperty LabelProperty = DependencyProperty.Register(
"Label",
typeof(String),
typeof(ProjectionControl),
new FrameworkPropertyMetadata("FLAT", OnLabelPropertyChanged));
private static void OnLabelPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs eventArgs)
{
((Label)FindName("myLabel")).Content = (string)GetValue("LabelProperty");
}
}
我知道在XAML中必须有更简单的方法,例如:
...
<Label Content="{Binding ...point to the Label property... }"/>
...
但是我尝试了很多组合(RelativeSource / Pah,Source / Path,x:Reference,只写属性名......)并且没有任何效果......
我是WinForms的专家,并且在某些时候学习WPF,但这些事情对我来说仍然是陌生的。
答案 0 :(得分:2)
您只需绑定到Label
属性
<Label Content="{Binding Label}"/>
此外,您可能需要将DataContext
设置为UserControl
xaml
<UserControl x:Class="WpfApplication10.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Name="UI"> // Set a name
<Grid DataContext="{Binding ElementName=UI}"> //Set DataContext using the name of the UserControl
<Label Content="{Binding Label}" />
</Grid>
</UserControl>
代码:
public partial class MyUserControl : UserControl
{
public MyUserControl()
{
InitializeComponent();
}
public static readonly DependencyProperty LabelProperty = DependencyProperty.Register(
"Label", typeof(String),typeof(MyUserControl), new FrameworkPropertyMetadata("FLAT"));
public string Label
{
get { return (string)GetValue(LabelProperty); }
set { SetValue(LabelProperty, value); }
}
}
的Xaml:
<UserControl x:Class="WpfApplication10.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Name="UI">
<Grid DataContext="{Binding ElementName=UI}">
<TextBlock Text="{Binding Label}" />
</Grid>
</UserControl>