开发者

How to initialize UserControl's CLR property in the following case?

开发者 https://www.devze.com 2023-01-08 17:36 出处:网络
I’ve created UserControl: public partial class MyTemplate : UserControl { publicMyUser User { get; set; }

I’ve created UserControl:

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

And then have written the following code in the main window’s xaml

<Window.Resources>
    <DataTemplate x:Key="My">
      <local:MyTemplate Margin="10"/>
    </DataTemplate>
<Window.Resources>
<ListBox x:Name="MyMainList"
       开发者_如何学JAVAItemTemplate="{StaticResource My}">
             ItemsSource="{Binding Path=MyTimelineTweets}"
             IsSynchronizedWithCurrentItem="True"> 

Where MyTimelineTweets has type ObservableCollection and MyTemplate user control shows data from MyFavouriteClass.

The question is:

How can I initialize MyTemplate.User in the xaml or in the code behind? //If the information about User is accessible only at the window level.


Make User a dependency property and then bind it similarly to this:

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

To make User a dependency property:

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

精彩评论

暂无评论...
验证码 换一张
取 消