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

2 に答える 2

17

これが、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などの行に沿って、そのテキストボックスのような名前を付けるという伝統に従います。これにより、将来、テンプレートを作成しながら、コードビハインドを同じに保つことができます。

于 2008-09-16T21:06:29.710 に答える
1

UserControl のコンストラクターで DataContext をこれに設定し、パスのみでバインドすることができます。

CS:

DataContext = this;

XAML:

<TextBox Margin="8" Text="{Binding Text} />
于 2010-01-03T19:04:59.487 に答える