我对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>
当视图渲染,我只能看空 文本框。我不明白什么是错的..?
你不加'propertiesList'集合中的任何东西。 – dymanoid
'MyModel.Add(m);'wat。帮助您在调试器中逐步执行代码。 https://msdn.microsoft.com/en-us/library/sc65sadd.aspx – Will
在propertiesList中添加了项目,但仍然没有效果。问题仍然是一样的。 –