我如何使用 WPF 中的列表填充数据网格中的组合框
How do i populate a Combobox in a Datagrid with a List in WPF
如何将包含项目的列表添加到数据网格内的组合框?
在 Datagrid 之外(对于普通的组合框)我可以做
List<string> myStringList = new List<string>();
myStringList.Add("Item 1");
myStringList.Add("Item 2");
ComboTest.ItemsSource = myStringList;
这将使用 'Item 1' 和 'Item 2'
这两个选项填充 ComboTest 组合框
从 XML 方面我无法使用 ItemsSource="{Binding ...}
选项填充它
XML 代码如下所示
<DataGridComboBoxColumn x:Name="comboTest" Width="*">
<DataGridComboBoxColumn.Header>
<TextBlock Text="Status" TextWrapping="Wrap"/>
</DataGridComboBoxColumn.Header>
</DataGridComboBoxColumn>
并且前面提到的两个选项都不能与 <DataTemplate>
中的组合框一起使用。
如果我将组合框放入 <DataTemplate>
中,它会显示组合框但为空,我将无法通过 C# 代码为其赋值。如果我使用上面显示的代码,它甚至根本不会显示组合框
例如,您可以使用添加到 window 或用户控件的 XAML 标记中的 CollectionViewSource
:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="Window26" Height="450" Width="800">
<Window.Resources>
<CollectionViewSource x:Key="items" />
</Window.Resources>
...
以编程方式将其 Source
属性 设置为您的列表:
(Resources["items"] as CollectionViewSource).Source = myStringList;
...并将该列绑定到 XAML 标记中的 CollectionViewSource
:
<DataGridComboBoxColumn ItemsSource="{Binding Source={StaticResource items}}" />
如何将包含项目的列表添加到数据网格内的组合框?
在 Datagrid 之外(对于普通的组合框)我可以做
List<string> myStringList = new List<string>();
myStringList.Add("Item 1");
myStringList.Add("Item 2");
ComboTest.ItemsSource = myStringList;
这将使用 'Item 1' 和 'Item 2'
这两个选项填充 ComboTest 组合框从 XML 方面我无法使用 ItemsSource="{Binding ...}
选项填充它
XML 代码如下所示
<DataGridComboBoxColumn x:Name="comboTest" Width="*">
<DataGridComboBoxColumn.Header>
<TextBlock Text="Status" TextWrapping="Wrap"/>
</DataGridComboBoxColumn.Header>
</DataGridComboBoxColumn>
并且前面提到的两个选项都不能与 <DataTemplate>
中的组合框一起使用。
如果我将组合框放入 <DataTemplate>
中,它会显示组合框但为空,我将无法通过 C# 代码为其赋值。如果我使用上面显示的代码,它甚至根本不会显示组合框
例如,您可以使用添加到 window 或用户控件的 XAML 标记中的 CollectionViewSource
:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="Window26" Height="450" Width="800">
<Window.Resources>
<CollectionViewSource x:Key="items" />
</Window.Resources>
...
以编程方式将其 Source
属性 设置为您的列表:
(Resources["items"] as CollectionViewSource).Source = myStringList;
...并将该列绑定到 XAML 标记中的 CollectionViewSource
:
<DataGridComboBoxColumn ItemsSource="{Binding Source={StaticResource items}}" />