2009-02-09 6 views
1

Je ne Konow comment mettre Path l'intérieur d'un UserControl basé sur un Parameter:Set Databinding chemin à l'intérieur UserControl

contrôle de l'utilisateur:

<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 derrière:

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("")); 
    } 

Et comment je prévois de l'utiliser:

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

DataContext sera obtenue à partir de l'objet parent et contiendra une classe de User avec une propriété FirstName à l'intérieur.

Le but est d'avoir un contrôle utilisateur qui peut être lié à n'importe quel chemin. Je sais que ça doit être super facile, mais je suis très nouveau dans cette technologie et je n'ai pas trouvé la résolution.

Répondre

1

J'ai enfin réussi à le faire, dans le 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)); 

le contrôle utilisateur dispose désormais d'une zone de texte sans se lier:

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

et c'est tout.

1

Lorsque vous écrivez dans votre XAML:

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

cette tente de vous lier à la propriété MyPath du DataContext du contrôle.

Pour lier la propre propriété du contrôle, je suppose que vous devez écrire smth comme:

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

Avez one of the cheat sheets près, juste au cas où;)

+0

Bien sûr, vous avez raison, mais mon intention était se lier au chemin qui est une valeur de cette propriété, pas à la propriété elle-même ... – bezieur

+0

Je ne comprends pas ... Comment ça? Vous faites essentiellement la même chose dans votre code. –