如何在以下情况下初始化UserControl的CLR属性?

问题描述:

我创建用户控件:如何在以下情况下初始化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? //如果关于用户的信息只能在窗口级别访问。

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