我创建了一个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,但这些东西对我来说仍然是陌生的。

===============>>#1 票数:2 已采纳

您只需绑定到Label属性即可

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

此外,您可能必须将DataContext设置为xamlUserControl

<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>

  ask by Libor translate from so

未解决问题?本站智能推荐: