c# - WPF中根据DataTable List生成几个Comboboxes
问题描述
我想根据数据表列表创建动态组合框。每次我向列表中添加一个新的数据表时,我都希望 UI 生成一个新的组合框,该组合框显示我从表中指定的列。我用 itemscontrol 和 datatemplate 进行了尝试,但没有像我想要的那样工作。
public List<DataTable> DtList
{
get { return dtList; }
set { dtList = value; }
}
<ItemsControl ItemsSource="{Binding Path=DtList}" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate >
<DataTemplate>
<ComboBox
VerticalContentAlignment="Center"
HorizontalContentAlignment="Left"
Margin="0,0,4,10"
Width="200"
BorderBrush="{DynamicResource ListBox.Static.Border}"
ItemsSource="{Binding DataSet}"
DisplayMemberPath="Element Name"
SelectedValuePath="ResourceType Name"
SelectedValue="{Binding SelectedRelationPath, Mode=TwoWay}"
/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
解决方案
我刚刚创建了一个样本,它对我有用
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
// this.DataContext = this; Uncomment this if code behind is your datacontext
InitializeComponent();
DataTable t1 = new DataTable();
t1.Columns.Add("Name");
t1.Columns.Add("Age");
t1.Rows.Add("A", "1");
t1.Rows.Add("B", "2");
DataTable t2 = new DataTable();
t2.Columns.Add("Name");
t2.Columns.Add("Age");
t2.Rows.Add("A", "1");
DtList = new List<DataTable> { t1, t2 };
}
private List<DataTable> dtList;
public List<DataTable> DtList
{
get { return dtList; }
set
{
dtList = value;
OnPropertyChanged("DtList");
}
}
private string selectedName;
public string SelectedName
{
get { return selectedName; }
set
{
selectedName = value;
OnPropertyChanged("SelectedName");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler == null) return;
handler(this, new PropertyChangedEventArgs(name));
}
}
在您的 Xaml 中,将其添加到您的窗口或 UserControl 标记中
x:Name="windowName"
现在这样做
<StackPanel>
<ItemsControl ItemsSource="{Binding Path=DtList}" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate >
<DataTemplate>
<ComboBox
VerticalContentAlignment="Center"
HorizontalContentAlignment="Left"
Margin="0,0,4,10"
Width="200"
ItemsSource="{Binding}"
DisplayMemberPath="Name"
SelectedValuePath="Age"
SelectedValue="{Binding Path=SelectedName,ElementName=windowName}"
/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
这对我来说很好。
推荐阅读
- java - 如何使用 jpa 运行存储过程 CREATE 查询
- ios - 如何使用集合视图/ segue 传递数据?
- python - 无法将自定义数据集加载到经过预训练以进行特征提取的 cnn
- python - 尝试运行 Stanford CoreNLP 时出现预期 EOF 错误
- python - 使用 TkInter 设置不可交互(点击)覆盖
- reactjs - 如何使用 Unicode 和 React 显示 Fontawesome 图标?
- jupyter-notebook - jupyter notebook 只接受大写字母作为输入 IN [ ],不接受 [ ]
- git - 维护远程存储库的精确深拷贝
- c - 在浮点输入中派生十进制数有时会将该值减去 1
- ngrx - 如何扩展 EntityCollectionReducerMethods NgRx 数据