首页 / 知识

关于wpf:公开DependencyProperty

2023-04-16 04:18:00

关于wpf:公开DependencyProperty

Expose DependencyProperty

开发WPF UserControls时,将子控件的DependencyProperty公开为UserControl的DependencyProperty的最佳方法是什么? 下面的示例显示我当前如何在UserControl内部公开TextBox的Text属性。 当然有更好/更简单的方法可以做到这一点吗?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<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的名称引用属性来实现。

1
2
3
4
5
6
7
<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之类的名称命名诸如文本框之类的东西的传统,以便将来您可以将其模板化,而将代码隐藏在后面。


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

CS:

1
DataContext = this;

XAML:

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

方法显示控件属性

最新内容

相关内容

猜你喜欢