问题
I am a newbie in WPF. I am following MVVM pattern. I have listbox in my mainwindow which has list of items. I also have a grid which is empty on startup. Now here is the query, on selecting the item from listbox, I want to generate labels, buttons, Checkboxes and textboxes dynamically rather than using toolbox.
ListBox & Grid in MainWindow:
<ListBox Name="ButtonPanel" ItemsSource="{Binding BoardTabs}" SelectedItem="{Binding SelectedTab, Mode=TwoWay}" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button Margin="0,27,0,0" Content="{Binding TabName}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Grid Height="461" HorizontalAlignment="Left" Margin="139,0,0,0" Name="grid1" VerticalAlignment="Top" Width="339" >
</Grid>
TabName is as string which is part of my model class.
ViewModel Class:
public List<Product> m_BoardTabs;
public ProductViewModel()
{
m_BoardTabs = new List<Product>()
{
new Product() {TabName = "A"},
new Product() {TabName = "B"},
new Product() {TabName = "C"},
};
}
public List<Product> BoardTabs
{
get
{
return m_BoardTabs;
}
set
{
m_BoardTabs = value;
}
}
private Product m_SelectedItem;
public Product SelectedTab
{
get
{
return m_SelectedItem;
}
set
{
m_SelectedItem = value;
NotifyPropertyChanged("SelectedTab");
}
}
Demonstration:
ListBox has 3 items. A, B, C
On selecting A, in my grid, I want to display L1, L2, L3 in stack order. B1, B2, B3 in stack order, C1, C2, C3 and T1, T2, T3 so on, where L is label, B is button, T is textbox and C is checkbox.
On selecting B, in my grid, I want to display L5, L6, L7 in stack order. B5, B6, B7 in stack order, C5, C6, C7 and T5, T6, T7 so on, where L is label, B is button, T is textbox and C is checkbox.
Same with Selecting C. Although its easy to create labels in application with the help of toolbox.
Is there a way I can generate them inside the grid based on selected item from Listbox?
回答1:
Yes.
What you need is different DataTemplates
for each case where you can define the structure of your desired controls and a DataTemplateSelector
to set the actual template for your Grid
.
Find more here
来源:https://stackoverflow.com/questions/12726178/how-to-generate-labels-buttons-checkboxes-and-textboxes-dynamically-in-wpf-app