2011-12-17 5 views
0

MyObjectの場合はDataTemplateを作成しています。 MyObjectは、例えば、StackPanel、すなわちpublic StackPanel MyStackPanelを含む。私はMyStackPanelをMyObjectのDataTemplateにどのように挿入できますか?UserControlを挿入するDataTemplate

+0

うーん、DataTemplatesが通常使用するコントロールの消費者のために意図されています。デフォルトのテンプレートを作成しようとしていますか? –

答えて

1

これは行うことができますが、私はあなたがしたい理由は分かりません。

この例では、オブジェクトタイプとして "Customer"を使用し、その中にボタンを含みます(ただし、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

このようなことはできません。テンプレートは実行されたビルドプランであり、特定のインスタンスや特定のインスタンスへの参照を含んでいません。

関連する問題