【问题标题】:Set Databinding Path inside UserControl在 UserControl 中设置数据绑定路径
【发布时间】:2009-02-09 09:45:12
【问题描述】:

我不知道如何根据ParameterUserControl 中设置Path

用户控制:

<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属性。

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

【问题讨论】:

    标签: c# wpf data-binding dependency-properties


    【解决方案1】:

    我终于在代码中做到了:

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

      当您在 XAML 中编写时:

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

      这会尝试将您绑定到控件的 DataContext 的 MyPath 属性。

      要绑定到控件自己的属性,我猜你应该这样写:

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

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

      【讨论】:

      • 当然,你是对的,但我的意图是绑定到作为该属性值的路径,而不是绑定到属性本身...
      • 我不明白...怎么样?您在代码中的操作基本相同。
      猜你喜欢
      • 2021-03-23
      • 1970-01-01
      • 2020-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多