tags:

views:

139

answers:

2

I don't konow how to set Path inside UserControl based on 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 obtain from parent object, and contains a class of User with 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 knew to that technology and I couldn't find the resolution.

A: 

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.

bezieur
+1  A: 

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 ;)

Yacoder
Sure, you're right, but my intention was to bind to the path which is a value of that property, not to the property itself...
bezieur
I don't get it... How's that? You are doing basically the same in your code.
Yacoder