0

我创建了一个 UserControl,它具有一个名为CustomLabel的 String 类型的依赖项属性。

该控件包含应显示CustomLabel属性值的 Label。

我可以使用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 一段时间,但这些东西对我来说仍然是陌生的。

4

1 回答 1

2

你可以绑定到Label属性

<Label Content="{Binding Label}"/>

此外,您可能必须DataContextUserControl您的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); }
    }
}

xml:

<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>
于 2013-04-16T01:21:50.657 回答