2016-11-17 116 views
0

我對WPF很新穎。我試圖在MVVM中動態地創建控件,但控件不會呈現在視圖中。我想要在視圖上創建一些標籤和文本框。在MVVM中動態創建控件

下面是我的代碼:

型號代碼

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

    public string KeyValue 
    { 
     get; 
     set; 
    } 
} 

模型視圖代碼

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); 

    } 
} 

查看代碼(由用戶控制)

<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> 

當視圖渲染,我只能看空 文本框。我不明白什麼是錯的..?

+4

你不加'propertiesList'集合中的任何東西。 – dymanoid

+0

'MyModel.Add(m);'wat。幫助您在調試器中逐步執行代碼。 https://msdn.microsoft.com/en-us/library/sc65sadd.aspx – Will

+0

在propertiesList中添加了項目,但仍然沒有效果。問題仍然是一樣的。 –

回答

2

按我的評論:

DataTemplate接收個人項目作爲其DataContext,所以你只需要包括像你的綁定路徑內的物品等級屬性名稱:

<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錯誤:40:BindingExpression路徑錯誤:' – Tomtom