2012-05-17 38 views
1

我有類的MyUserControl,它擴展了用戶控件,使用參數:WPF C#傳遞XAML對象作爲參數

namespace MyNameSpace 
{ 
    public partial class MyUserControl: UserControl 
    { 
     public MyUserControl() 
     { 
      InitializeComponent(); 
     } 

     private Control _owner; 
     public Control Owner 
     { 
      set { _owner = value; } 
      get { return _owner; } 
     } 
    } 
} 

我怎樣才能通過,例如,一個網格內的XAML作爲參數?

<Window x:Class="MyNameSpace.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525" 
     xmlns:my="clr-namespace:MyNameSpace"> 
    <Grid x:Name="grid1"> 
     <my:MyUserControl x:Name="myUserControl1" Parent="*grid1?*" /> 
    </Grid> 
</Window> 

回答

3

您將需要實現所有者財產作爲的DependencyProperty。這是你需要爲用戶控件的代碼:

public static readonly DependencyProperty OwnerProperty = 
    DependencyProperty.Register("Owner", typeof(Control), typeof(MyUserControl), 
    new FrameworkPropertyMetadata(null, OnOwnerPropertyChanged) 
); 

private static void OnOwnerPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e) 
{ 
    ((MyUserControl)source).Owner = (Control)e.NewValue; 
} 

public Control Owner 
{ 
    set { SetValue(OwnerProperty, value); } 
    get { return (Control)GetValue(OwnerProperty); } 
} 

然後在XAML,你將能夠設置該屬性爲你所期望的:

<Button x:Name="Button1" Content="A button" /> 
<my:MyUserControl Owner="{Binding ElementName=Button1}" x:Name="myUserControl1" /> 

(請注意,你的榜樣就不行,因爲GRID1繼承型FrameworkElement的,不控制。你需要改變業主屬性類型FrameworkElement的能夠將其設置爲GRID1

有關依賴屬性的詳細信息,請參閱本優秀教程:http://www.wpftutorial.net/dependencyproperties.html

0

爲ealier描述ü應該使用DependancyProperty用於綁定,和u還可以使用RelativeSource

Parent={Binding RelativeSource={RelativeSource AncestorType=Grid}}