2016-11-17 67 views
0

私はWPFをかなり新しくしています。 MVVMでコントロールを動的に作成しようとしていますが、コントロールは表示されません。私はいくつかのラベルとテキストボックスを作成したいと思っています。MVVMで動的にコントロールを作成する

以下は私のコードです:

public class MyModel 
{ 
    public string KeyName 
    { 
     get; 
     set; 
    } 

    public string KeyValue 
    { 
     get; 
     set; 
    } 
} 

のModelViewコード

モデルのコード

<Grid> 
    <ItemsControl ItemsSource="{Binding Properties}"> 
     <ItemsControl.ItemTemplate> 
      <DataTemplate DataType="{x:Type cw:MyModel}"> 
       <StackPanel Orientation="Horizontal"> 
        <Label Margin="10" Content="{Binding Properties.KeyName}"></Label> 
        <TextBox Margin="10" Text="{Binding Properties.KeyValue}" Width="250"></TextBox> 
       </StackPanel> 
      </DataTemplate> 
     </ItemsControl.ItemTemplate> 
    </ItemsControl> 
</Grid> 

は、ビューのレンダリング(ユーザーコントロールである)

public class MyViewModel 
{ 
    private ObservableCollection<MyModel> propertiesList = new ObservableCollection<MyModel>(); 
    public CustomWriterViewModel() 
    { 

     GetMyProperties() 

    } 


    public ObservableCollection<MyModel> Properties 
    { 
     get { return propertiesList; } 
    } 

    private void GetMyProperties() 
    { 
     MyModel m = new MyModel(); 
     m.KeyName = "Test Key"; 
     m.KeyValue = "Test Value"; 
     MyModel.Add(m); 

    } 
} 

コードの表示、私は空しか見ることができません テキストボックス。私は何が間違っているのか理解できません..私のコメントを1として

+4

DataTemplateは、したがって、あなただけのようなあなたの結合パス内のアイテム・レベルのプロパティ名を含める必要があり、そのDataContextとして個々のアイテムを受け取ります'propertiesList'コレクション内のものです。 – dymanoid

+0

'MyModel.Add(m);' wat。デバッガでコードをステップ実行するときに役立ちます。 https://msdn.microsoft.com/en-us/library/sc65sadd.aspx – Will

+0

はpropertyListに項目を追加しましたが、効果はありません。それでも問題は同じです。 –

答えて

2

:あなたは追加しないでください

<DataTemplate DataType="{x:Type cw:MyModel}"> 
    <StackPanel Orientation="Horizontal"> 
     <Label Margin="10" Content="{Binding KeyName}"></Label> 
     <TextBox Margin="10" Text="{Binding KeyValue}" Width="250"></TextBox> 
    </StackPanel> 
</DataTemplate> 
+0

はい。出来た。ありがとうございます... –

+0

あなたは出力ウィンドウでそのようなバインディングエラーを特定することができます。このようなエラーは、 'System.Windows.Data Error:40:BindingExpression path error:'のようなものです – Tomtom

関連する問題