c# - 将 DependencyProperty 转发到用户控件中包含的控件

我正在尝试创建一个用户控件,其中包含一些 DependencyProperties,这些属性会转发给用户控件中的子控件。经过几次尝试,我开始工作了。为了测试一个小例子。

在示例中,我有一个名为 Ctrl 的用户控件,它只包含一个 TextBox 并公开 TextBox 的 Text 属性。此控件用于包含绑定(bind)到同一属性的 TextBox 和我的自定义 Ctrl 的窗口。

用户控制

XAML

<UserControl x:Class="trying.Ctrl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    DataContext="{Binding RelativeSource={RelativeSource self}}"
    Height="Auto" Width="Auto">
    <TextBox Text="{Binding MyText}" />
</UserControl>

代码隐藏

using System.Windows;
using System.Windows.Controls;

namespace trying
{
    public partial class Ctrl : UserControl
    {
        public static readonly DependencyProperty MyTextProperty = DependencyProperty.Register(
            "MyText",
            typeof( string ),
            typeof( UserControl ),
            new FrameworkPropertyMetadata( default(string), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
        public string MyText
        {
            get { return (string)GetValue( MyTextProperty ); }
            set { SetValue( MyTextProperty, value ); }
        }

        public Ctrl()
        {
            InitializeComponent();
        }
    }
}

窗口

XAML

<Window x:Class="trying.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:cc="clr-namespace:trying"
    DataContext="{Binding RelativeSource={RelativeSource self}}"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <TextBox Grid.Row="0" VerticalAlignment="Center" HorizontalAlignment="Center" Text="{Binding DisplayText}" />
        <cc:Ctrl Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center" MyText="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DisplayText}" />
    </Grid>
</Window>

代码隐藏

using System.Windows;
using System.ComponentModel;

namespace trying
{
    public partial class Window1 : Window, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected void NotifyPropertyChanged( string propertyName )
        {
            if( PropertyChanged != null )
                PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
        }

        private string m_displayText = "asdf";
        public string DisplayText
        {
            get { return m_displayText; }
            set
            {
                m_displayText = value;
                NotifyPropertyChanged( "DisplayText" );
            }
        }

        public Window1()
        {
            InitializeComponent();
        }
    }
}

问题

我是如何发布代码的。我现在的问题是:我做错了什么我必须使用绑定(bind)

 MyText="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}

当绑定(bind) CtrlMyText 属性时,不能像我绑定(bind)原始 TextBox 时那样简单绑定(bind)吗?

如果我不以这种方式绑定(bind),它将无法工作,并且我会收到警告

  System.Windows.Data Error: 39 : BindingExpression path error: 'DisplayText' property
  not found on 'object' ''Ctrl' (Name='')'. BindingExpression:Path=DisplayText; 
  DataItem='Ctrl' (Name=''); target element is 'Ctrl' (Name=''); target property
  is 'MyText' (type 'String')

我必须更改什么才能像原始 TextBox 那样绑定(bind)?

执行期间。

最佳答案

UserControlDataContext 指向其自身,因此控件实例上的任何绑定(bind)都将查看 Ctrl 实例而不是继承的 DataContext

尝试在树的下方设置 DataContext:

<UserControl 
   x:Class="trying.Ctrl" x:Name="root"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   Height="Auto" Width="Auto"
>
   <TextBox 
      DataContext="{Binding ElementName=root}"
      Text="{Binding MyText}" 
   />
</UserControl>

https://stackoverflow.com/questions/13307970/

相关文章:

php - Wordpress wp_editor 不更新文本区域 $_POST 数据

python - 将 Python 正则表达式用于 Twitter 数据

Wordpress - 在配置文件页面上删除 "Roles"

sql - 当一个值为 null 时未拾取不匹配

google-chrome - "Extension Install Failure: Packag

php - Wordpress 主题选项不会保存

.net - 即使所有新发布者都有签名证书,未知发布者警告是否真的会出现?

python - 从 `scipy.ndimage.map_coordinates` 输出向量/数组

php - 在 foreach 循环中使用数组变量

.net - 如果我有一个返回不同列表的方法,我应该让它返回 ISet 而不是 IEnumer