2016-11-17 120 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