代码之家  ›  专栏  ›  技术社区  ›  Joseph Sturtevant

暴露依赖属性

  •  18
  • Joseph Sturtevant  · 技术社区  · 17 年前

    在开发WPF用户控件时,将子控件的DependencyProperty作为UserControl的DependencyProperty公开的最佳方法是什么?以下示例显示了我当前将如何在UserControl中公开TextBox的Text属性。当然有更好/更简单的方法来实现这一点吗?

        <UserControl x:Class="WpfApplication3.UserControl1"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
            <StackPanel Background="LightCyan">
                <TextBox Margin="8" Text="{Binding Text, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" />
            </StackPanel>
        </UserControl>
    
        using System;
        using System.Windows;
        using System.Windows.Controls;
        
        namespace WpfApplication3
        {
            public partial class UserControl1 : UserControl
            {
                public static DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(UserControl1), new PropertyMetadata(null));
                public string Text
                {
                    get { return GetValue(TextProperty) as string; }
                    set { SetValue(TextProperty, value); }
                }
        
                public UserControl1() { InitializeComponent(); }
            }
        }
    
    2 回复  |  直到 5 年前
        1
  •  17
  •   user7116    17 年前

    这就是我们在团队中的做法,没有RelativeSource搜索,而是通过命名UserControl并用UserControl的名称引用属性。

    <UserControl x:Class="WpfApplication3.UserControl1" x:Name="UserControl1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <StackPanel Background="LightCyan">
            <TextBox Margin="8" Text="{Binding Path=Text, ElementName=UserControl1}" />
        </StackPanel>
    </UserControl>
    

    有时我们发现自己做了太多UserControl的东西,并且经常减少我们的使用。我也会遵循按照PART_TextDisplay或其他方式命名文本框的传统,这样将来你就可以将其模板化,同时保持代码不变。

        2
  •  1
  •   some_engineer    16 年前

    您可以在UserControl的构造函数中将DataContext设置为此值,然后仅通过路径绑定。

    反恐精英:

    DataContext = this;
    

    XAML:

    <TextBox Margin="8" Text="{Binding Text} />