将 UserControl 绑定到其自己的 dependencyProperty 不起作用

2024-03-18

我遇到一个问题,当父级将该对象设置为数据绑定时,我无法创建使用自定义对象的属性的用户控件。

尝试解释一下我在这里的意思是代码。 自定义对象:

public class MyObj
{
    public string Text { get; set; }

    public MyObj(string text)
    {
        Text = text;
    }
}

用户控制背后的代码:

/// <summary>
/// Interaction logic for MyControl.xaml
/// </summary>
public partial class MyControl : UserControl
{
    public static readonly DependencyProperty ObjectProperty =
        DependencyProperty.Register("Object", typeof (MyObj), typeof (MyControl), new PropertyMetadata(default(MyObj)));

    public MyObj Object
    {
        get { return (MyObj) GetValue(ObjectProperty); }
        set { SetValue(ObjectProperty, value); }
    }

    public MyControl()
    {
        InitializeComponent();
    }
}

用户控制XAML:

<UserControl x:Class="Test.MyControl"
         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" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300" DataContext="{Binding RelativeSource={RelativeSource Self}}">
<TextBlock Text="{Binding Object.Text}"/>

所以我所期望的是 MyControl 显示一个 TextBlock,其中的文本显示 MyObj.Text 中的任何字符串;

如果我在代码中添加控件,没有任何绑定,那么这可以正常工作,例如

MyControl myControl = new MyControl(){ Object = new MyObj("Hello World!") };
grid.Children.Add(myControl);

但是,如果我尝试使用数据绑定,则不会显示任何内容,这是 MainWindow 的代码。

隐藏代码:

public partial class MainWindow : Window, INotifyPropertyChanged
{
    private MyObj _Object;
    public MyObj Object
    {
        get { return _Object; }
        set
        {
            _Object = value;
            OnPropertyChanged("Object");
        }
    }

    public MainWindow()
    {
        InitializeComponent();

        Object = new MyObj("HELLO");
    }

    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

XAML:

谁能指出我正确的方向,我想这与在 UserControl 上使用相对源绑定有关,但我不确定。

Thanks


我个人从未在 UserControl 上使用过相对自绑定,因此我不确定它是否有效。您可以尝试设置x:Name你的UserControl,并在绑定中使用它。

<UserControl x:Class="Test.MyControl"
             ...
             x:Name="window">
    <TextBlock Text="{Binding ElementName=window, Path=Object.Text}"/>
</UserControl>

请注意,如果数据绑定在运行时绑定失败,您还应该在“输出”窗口中看到相关的错误消息。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 UserControl 绑定到其自己的 dependencyProperty 不起作用 的相关文章

随机推荐