我创建了UserControl:
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的类型为ObservableCollection,MyTemplate用户控件显示来自MyFavouriteClass的数据。
问题是:
如何在xaml或后面的代码中初始化MyTemplate.User? //如果只能在窗口级别访问有关用户的信息。
答案 0 :(得分: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); }
}