How to achieve data binding using a user control in WPF?

I am new to WPF and I have some problems getting the data binding to work as I want. I wrote a user control that contains a TextBox whose Text-Property I want to bind to a property of my UserControl, which I want to bind to something else again.

What am I missing?

Xaml

<!-- User Control -->
<TextBox Text="{Binding Path=TheText}" />

<!-- Window -->
<WpfApplication1:SomeControl TheText="{Binding Path=MyStringProp}" />

FROM#

// User Control ----

public partial class SomeControl : UserControl
{
    public DependencyProperty TheTextProperty = DependencyProperty
        .Register("TheText", typeof (string), typeof (SomeControl));

    public string TheText
    {
        get
        {
            return (string)GetValue(TheTextProperty);
        }
        set
        {
            SetValue(TheTextProperty, value);
        }
    }

    public SomeControl()
    {
        InitializeComponent();
        DataContext = this;
    }
}

// Window ----

public partial class Window1 : Window
{
    private readonly MyClass _myClass;

    public Window1()
    {
        InitializeComponent();

        _myClass = new MyClass();
        _myClass.MyStringProp = "Hallo Welt";

        DataContext = _myClass;
    }
}

public class MyClass// : DependencyObject
{
//  public static DependencyProperty MyStringPropProperty = DependencyProperty
//      .Register("MyStringProp", typeof (string), typeof (MyClass));

    public string MyStringProp { get; set; }
//  {
//      get { return (string)GetValue(MyStringPropProperty); }
//      set { SetValue(MyStringPropProperty, value); }
//  }
}

Best regards
Oliver Hanappi

PS: I tried to implement the INotifyPropertyChanged interface in my user control, but that didn't help.

+3
source share
2 answers

Text TextBox TheText UserControl, , ? , . ( RelativeSource FindAncestor), - UserControl "" XAML :

<UserControl ...
    x:Name="me" />
    <TextBox Text="{Binding TheText,ElementName=me}" />
</UserControl>

TextBox , ( ) "SomeControl.TheText" - - , , , INotifyPropertyChanged MyClass, , .

+2

. , .

SomeControl.DataContext SomeControl, TheText="{Binding Path=MyStringProp}" Source SomeControl, MyClass, .

, , Visual Studio. , MyStringProp SomeControl, .

, WPF , , . WPF , , .

+1

Source: https://habr.com/ru/post/1713732/


All Articles