如何在WPF App中动态生成标签,按钮,复选框和文本框 [英] How to generate labels, buttons, Checkboxes and textboxes dynamically in WPF App
问题描述
我是WPF的新手.我正在关注MVVM模式.我的主窗口中有列表框,其中包含项目列表.我也有一个网格,它在启动时是空的.现在是查询,在从列表框中选择项目时,我想动态生成标签,按钮,复选框和文本框,而不是使用工具箱.
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.
列表框&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 是作为字符串的,属于我的模型类.
TabName is as string which is part of my model class.
ViewModel类:
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");
}
}
演示:
ListBox有3个项目.A,B,C
ListBox has 3 items. A, B, C
在选择A时,在我的网格中,我想按堆栈顺序显示L1,L2,L3.B1,B2,B3按堆栈顺序排列,C1,C2,C3和T1,T2,T3依此类推,其中L是标签,B是按钮,T是文本框,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.
在选择B时,在我的网格中,我想按堆栈顺序显示L5,L6,L7.B5,B6,B7按堆栈顺序排列,C5,C6,C7和T5,T6,T7依此类推,其中L是标签,B是按钮,T是文本框,C是复选框.
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.
与选择C相同.尽管借助工具箱很容易在应用程序中创建标签.
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?
推荐答案
是.
在每种情况下,您需要的是不同的 DataTemplates
,您可以定义所需控件的结构和 DataTemplateSelector
来设置 Grid的实际模板
.
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
.
在此处
这篇关于如何在WPF App中动态生成标签,按钮,复选框和文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!