4

親がそのオブジェクトをデータバインドに設定している場合、カスタムオブジェクトのプロパティを使用するユーザーコントロールを作成できないという問題があります。

ここで私が意味することを説明しようとするのはコードです。カスタム オブジェクト:

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 が MyObj.Text に含まれる文字列を示すテキストを含む TextBlock を表示することだけが期待されます。

バインディングなしでコードにコントロールを追加すると、これは問題なく機能します。

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 で相対ソース バインディングを使用することと関係があると思いますが、よくわかりません。

ありがとう

4

2 に答える 2