代码之家  ›  专栏  ›  技术社区  ›  Roman Motyka James Nugent

在用户控件内设置数据绑定路径

  •  1
  • Roman Motyka James Nugent  · 技术社区  · 16 年前

    我不知道怎么设置 Path 在一个 UserControl 基于 Parameter :

    用户控件:

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

    代码隐藏:

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

    以及我打算如何使用它:

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

    DataContext 将从父对象获取,并包含 User 用一个 FirstName 财产在里面。

    目标是拥有一个可以绑定到任何路径的用户控件。 我知道这一定非常简单,但我对这项技术还很陌生,我找不到分辨率。

    2 回复  |  直到 14 年前
        1
  •  1
  •   Roman Motyka James Nugent    16 年前

    我终于做到了,用代码:

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

    用户控件现在有一个不带绑定的文本框:

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

    就这样。

        2
  •  1
  •   Community Mohan Dere    8 年前

    当您在XAML中编写时:

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

    数据上下文 控制权。

    要绑定到控件本身的属性,我想您应该编写如下smth:

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

    拥有 one of the cheat sheets 在附近,以防万一;)

    推荐文章