18

在开发 WPF UserControls 时,将子控件的 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(); }
        }
    }
4

2 回答 2

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 或其他方式命名文本框之类的传统,以便将来您可以将其模板化,但保持代码隐藏相同。

于 2008-09-16T21:06:29.710 回答
1

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

CS:

DataContext = this;

XAML:

<TextBox Margin="8" Text="{Binding Text} />
于 2010-01-03T19:04:59.487 回答