2008-09-16 47 views
18

當開發WPF UserControls時,將子控件的DependencyProperty公開爲UserControl的DependencyProperty的最佳方式是什麼?以下示例顯示了當前如何將TextBox內的Text屬性公開在UserControl中。當然,有一個更好/更簡單的方法來實現這一目標?公開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

這就是我們如何在我們的團隊做這件事,沒有的RelativeSource搜索,而不是通過命名的用戶控件和引用由用戶控件的名稱屬性。

<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

這種方式最適合在Silverlight 4中不存在 'FindAncestor' – 2010-09-03 04:11:44

+0

這爲我工作,但它看起來像你可以不使用相同的`x:Class`和`x:Name`。我必須有一個像`WpfApplication1.SliderLabel`這樣的類,並且給了它一個像SliderLabelControl這樣的名字。否則它會抱怨這個名字已經存在。 – 2016-03-13 22:42:01

1

您可以在UserControl的構造函數中將DataContext設置爲此,然後僅通過路徑進行綁定。

CS:

DataContext = this; 

XAML:

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