Roman Motyka
Roman Motyka

Reputation: 649

Set Databinding Path inside UserControl

I don't konow how to set Path inside a UserControl based on a Parameter:

User control:

<UserControl x:Class="WpfApplication3.TestControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:diagnostics="clr-namespace:System.Diagnostics;assembly=WindowsBase">
    <Grid>
        <TextBox Text="{Binding Path=MyPath}"/>
    </Grid>
</UserControl>

Code behind:

   public partial class TestControl : UserControl
    {
        public string MyPath
        {
            get { return (string)GetValue(MyPathProperty); }
            set { SetValue(MyPathProperty, value); }
        }
        public static readonly DependencyProperty MyPathProperty =
            DependencyProperty.Register("MyPath", typeof(string), typeof(TestControl), new UIPropertyMetadata(""));
    }

And how I plan to use it:

<local:TestControl MyPath="FirstName"></local:TestControl>

DataContext will be obtained from the parent object, and contains a class of User with a FirstName property inside.

The goal is to have a user control which can be bound to any path. I know it must be super easy, but I'm very new to that technology and I couldn't find the resolution.

Upvotes: 1

Views: 740

Answers (2)

Massimiliano
Massimiliano

Reputation: 16980

When you write in your XAML:

<TextBox Text="{Binding Path=MyPath}"/>

this tries to bind you to the MyPath property of the DataContext of the control.

To bind to the control's own property, I guess you should write smth like:

<TextBox Text="{Binding Path=MyPath, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"/>

Have one of the cheat sheets near, just in case ;)

Upvotes: 1

Roman Motyka
Roman Motyka

Reputation: 649

I've finally managed to do that, in code:

private static void MyPathChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    TestControl tc = d as TestControl;
    Binding myBinding = new Binding("MyDataProperty");
    myBinding.Mode = BindingMode.TwoWay;
    myBinding.Path = new PropertyPath(tc.MyPath);
    tc.txtBox.SetBinding(TextBox.TextProperty, myBinding);
}

public static readonly DependencyProperty MyPathProperty =
    DependencyProperty.Register("MyPath",
        typeof(string),
        typeof(TestControl),
        new PropertyMetadata("", MyPathChanged));

the user control now has a text box without binding:

 <TextBox x:Name="txtBox"></TextBox> 

and that's it.

Upvotes: 1

Related Questions