2010-07-21 111 views
0

我創建用戶控件:如何在以下情況下初始化UserControl的CLR屬性?

public partial class MyTemplate : UserControl 
{ 
    public MyUser User { get; set; } 
} 

然後寫了下面的代碼在主窗口的XAML

<Window.Resources> 
    <DataTemplate x:Key="My"> 
     <local:MyTemplate Margin="10"/> 
    </DataTemplate> 
<Window.Resources> 
<ListBox x:Name="MyMainList" 
     ItemTemplate="{StaticResource My}"> 
      ItemsSource="{Binding Path=MyTimelineTweets}" 
      IsSynchronizedWithCurrentItem="True"> 

凡MyTimelineTweets的類型是從MyFavouriteClass的ObservableCollection和MyTemplate的用戶控制顯示的數據。

的問題是:

我怎樣才能在XAML或在後面的代碼初始化MyTemplate.User? //如果關於用戶的信息只能在窗口級別訪問。

回答

1

User一個dependency property,然後同樣將其綁定到這一點:

<Window x:Name="window"> 
    ... 
    <local:MyTemplate Margin="10" User="{Binding Foo, ElementName=window}"/> 
    ... 
</Window> 

爲了User依賴屬性:

public static readonly DependencyProperty UserProperty = DependencyProperty.Register("User", 
    typeof(User), 
    typeof(MyTemplate)); 

public User User 
{ 
    get { return GetValue(UserProperty) as User; } 
    set { SetValue(UserProperty, value); } 

} 
+0

非常感謝。它應該有所幫助 – 2010-07-21 07:18:47

相關問題