DataTemplate inserting UserControl

本文关键字:UserControl inserting DataTemplate | 更新日期: 2023-09-27 18:18:04

我正在为MyObject创建DataTemplateMyObject包含,例如StackPanel命名为public StackPanel MyStackPanel。我怎么能插入MyStackPanel到MyObject的数据模板?

DataTemplate inserting UserControl

这是可以做到的,但是我不明白你为什么要这样做。

在这个例子中,我使用"Customer"作为对象类型,并在其中包含一个Button(但它也可以很容易地成为一个StackPanel)。

public class Customer : DependencyObject
{
    public Customer()
    {
        MyButton = new Button();
        MyButton.Content = "I'm a button!";
    }
    #region MyButton
    public Button MyButton
    {
        get { return (Button)GetValue(MyButtonProperty); }
        set { SetValue(MyButtonProperty, value); }
    }
    public static readonly DependencyProperty MyButtonProperty =
        DependencyProperty.Register("MyButton", typeof(Button), typeof(Customer));
    #endregion
}

我不确定你是否可以做到这一点,而不使你的对象成为DependencyObject并将嵌套控件定义为依赖属性。实现INotifyPropertyChanged可以作为一种替代方案(如果你的对象不能从DependencyObject继承),但我还没有测试过。

带有模板的主窗口:

<Window x:Class="TemplateTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:TemplateTest"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <DataTemplate DataType="{x:Type local:Customer}">
            <ContentPresenter Content="{Binding MyButton}" />
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <ItemsControl x:Name="CustomersList" />
    </Grid>
</Window>

正如你所看到的,我使用一个ContentPresenter来绑定来自对象的按钮。

你可以这样测试它:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        Loaded += (s, e) =>
            {
                var myCustomer1 = new Customer();
                var myCustomer2 = new Customer();
                var customers = new ObservableCollection<Customer>();
                customers.Add(myCustomer1);
                customers.Add(myCustomer2);
                CustomersList.ItemsSource = customers;
            };
    }
}

你不能那样做,模板是被执行的构建计划,它们不包含特定的实例或对特定实例的引用。