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

Nic*_*ams 3 c# data-binding wpf user-controls mvvm

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

试着解释一下我的意思是代码.自定义对象:

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

    public MyObj(string text)
    {
        Text = text;
    }
}
Run Code Online (Sandbox Code Playgroud)

用户控制代码背后:

/// <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();
    }
}
Run Code Online (Sandbox Code Playgroud)

用户控制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}"/>
Run Code Online (Sandbox Code Playgroud)

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

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

MyControl myControl = new MyControl(){ Object = new MyObj("Hello World!") };
grid.Children.Add(myControl);
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试使用数据绑定,则不显示任何内容,这里是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));
    }
}
Run Code Online (Sandbox Code Playgroud)

XAML:

任何人都可以指出我正确的方向,我想这与在UserControl上使用相对源绑定有关,但我不确定.

谢谢

Wil*_*ins 14

我个人从来没有在UserControl上使用相对自我绑定,所以我不确定它是否有效.您可以尝试设置x:Name您的UserControl,并在绑定中使用它.

<UserControl x:Class="Test.MyControl"
             ...
             x:Name="window">
    <TextBlock Text="{Binding ElementName=window, Path=Object.Text}"/>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

请注意,如果数据绑定在运行时无法绑定,您还应在"输出"窗口中看到相关的错误消息.

  • Upvote为"输出窗口"提示. (2认同)