WPF UserControlsを開発するとき、子コントロールのDependencyPropertyをUserControlのDependencyPropertyとして公開する最善の方法は何ですか?次の例は、現在、UserControl内のTextBoxのTextプロパティをどのように公開するかを示しています。確かにこれを達成するためのより良い/より簡単な方法がありますか?私たちは、むしろユーザーコントロールを命名し、UserControlの名前でプロパティを参照することにより、RelativeSource検索せずに、私たちのチームでそれをやっている方法ですExpose DependencyProperty
<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(); }
}
}
これは私のために働いたNO 'FindAncestor' –
がない場合、この方法は、しかし、それはあなたができるように見えるしていません、Silverlightの4で最高の作品同じ 'x:Class'と' x:Name'を使います。私は 'WpfApplication1.SliderLabel'のようなクラスを持っていなければならず、' SliderLabelControl'のような名前を付けました。そうでなければ、その名前はすでに存在していると訴えていました。 –