2011-12-17 94 views
0

我正在爲MyObject創建DataTemplate。例如,MyObject包含StackPanel,其名稱爲public StackPanel MyStackPanel。我如何將MyStackPanel插入到MyObject的DataTemplate中?DataTemplate插入UserControl

+0

嗯,的DataTemplates通常用於您的控件使用的消費者。你想創建一種...默認模板? – 2011-12-17 18:28:31

回答

1

這可以做到,但我不明白你爲什麼想要。

在這個例子中,我使用「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; 
      }; 
    } 
} 
0

你不能這樣做,模板正在構建被執行的計劃,它們不包含特定實例或對特定實例的引用。

相關問題