Microsoft Developer Microsoft Developer - 15 days ago 11
C# Question

Dynamically Create Controls in MVVM

I am pretty new to WPF. I am trying to create controls dynamically in MVVM but controls are not rendered on view. I want some number of label and textbox to be created on view.

Below is my code:

Model Code

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

public string KeyValue
{
get;
set;
}
}


ModelView Code

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

}
}


View Code(Which is user control)

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


When view renders, I can only see empty textbox. I cannot understand what is wrong..?

Answer

As per my comment:

The DataTemplate receives an individual item as its DataContext, therefore you only need to include item level property names within your binding paths like:

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