公开 DependencyProperty [英] Expose DependencyProperty

查看:21
本文介绍了公开 DependencyProperty的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When developing WPF UserControls, what is the best way to expose a DependencyProperty of a child control as a DependencyProperty of the UserControl? The following example shows how I would currently expose the Text property of a TextBox inside a UserControl. Surely there is a better / simpler way to accomplish this?

    <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(); }
        }
    }

推荐答案

这就是我们团队的做法,不使用 RelativeSource 搜索,而是通过命名 UserControl 并通过 UserControl 的名称引用属性.

That is how we're doing it in our team, without the RelativeSource search, rather by naming the UserControl and referencing properties by the UserControl's name.

<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've found ourselves making too many things UserControl's though, and have often times scaled back our usage. I'd also follow the tradition of naming things like that textbox along the lines of PART_TextDisplay or something, so that in the future you could template it out yet keep the code-behind the same.

这篇关于公开 DependencyProperty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆