2008-09-16 7 views
18

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

答えて

17

<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や何かの行に沿ってそのテキストボックスのような名前を付けるという伝統に従っています。そのため、将来的にはコードビハインドを同じままにしておくことができます。

+0

これは私のために働いたNO 'FindAncestor' –

+0

がない場合、この方法は、しかし、それはあなたができるように見えるしていません、Silverlightの4で最高の作品同じ 'x:Class'と' x:Name'を使います。私は 'WpfApplication1.SliderLabel'のようなクラスを持っていなければならず、' SliderLabelControl'のような名前を付けました。そうでなければ、その名前はすでに存在していると訴えていました。 –

1

これにUserControlのコンストラクタでDataContextを設定し、パスだけでバインドできます。

CS:

DataContext = this; 

XAML:

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

これは限られた規模でしか動作しません。あなたが本当にデータインターフェイスを必要とするならば、 –

関連する問題