暴露 DependencyProperty

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(); }
        }
    }
2个回答

18

这就是我们团队的做法,不使用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之类的,这样将来就可以将其模板化,同时保持代码后台不变。
Sometimes we have found ourselves making too many UserControl's though, and have often scaled back our usage. I would also follow the tradition of naming controls like that textbox along the lines of PART_TextDisplay or something similar, so that in the future it can be templated out while keeping the code-behind the same.

这种方法在Silverlight 4中效果最佳,因为它没有“FindAncestor”。 - Simon_Weaver
这对我有用,但似乎不能使用相同的 x:Classx:Name。我必须有一个类似于 WpfApplication1.SliderLabel 的类,并将其命名为 SliderLabelControl。否则它会抱怨名称已经存在。 - Adam Plocher

1

你可以在UserControl的构造函数中将DataContext设置为this,然后只需通过路径进行绑定。

CS:

DataContext = this;

XAML:

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

1
这只在有限的范围内有效。如果你真的需要一个数据上下文,那你就完了。 - Simon_Weaver

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接