wpf - 公开依赖项属性

标签 wpf data-binding user-controls

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

最佳答案

这就是我们在团队中进行此操作的方法,而无需使用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之类的名称命名诸如文本框之类的东西的传统,以便将来您可以将其模板化,同时保持其代码隐藏。

关于wpf - 公开依赖项属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76412/

相关文章:

wpf - 当Application.Current为NULL时如何退出wpf应用程序?

WPF 在 Windows XP 和 Windows 7 上的呈现方式不同

sql-server - WPF C# : How to set Dynamic Connection String of SQL Server local database

c# - 双向绑定(bind)不起作用

c# - 将 DataGridView 绑定(bind)到 List<>,某些属性不应显示

c# - 使用 JQuery 添加用户控件时出现 "Error executing child request for handler ' System.Web.UI.Page '."

c# - 具有事件的复合 WPF GUI 界面

WPF 绑定(bind)和资源查找复杂性

c# - 如何从 C# 面板控件中 Dispose() 特定用户控件?

c++ - 我想为每个组合框选择分配整数值并将它们集中打印在文本文件中