Подтвердить что ты не робот

Expose DependencyProperty

При разработке WPF UserControls лучший способ открыть DependencyProperty дочернего элемента управления как DependencyProperty UserControl? В следующем примере показано, как в настоящее время я обнаруживаю свойство Text для TextBox внутри UserControl. Разумеется, есть лучший/более простой способ сделать это?

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

Ответ 1

Вот как мы это делаем в нашей команде без поиска 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 или что-то в этом роде, так что в будущем вы можете его отформатировать, но сохранить код за тем же.

Ответ 2

Вы можете установить DataContext в конструктор UserControl, а затем просто привязать только путь.

CS:

DataContext = this;

XAML:

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