请帮助我了解如何在 WPF 的 DataGrid 中使用 ComboBoxColumn。 我正在尝试创建一个设备列表,其中每个设备在“日志”字段中都有动态状态列表。
<DataGrid AutoGenerateColumns="False" Margin="12,6,12,12" Name="dataGrid1" Grid.Row="1" SelectionUnit="FullRow">
<DataGrid.Columns>
...
<DataGridComboBoxColumn Header="Log"
ItemsSource="{Binding log, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:Device}}}"/>
</DataGrid.Columns>
</DataGrid>
public partial class MainWindow : Window
{
public ObservableCollection<Device> devices;
...
}
public MainWindow()
{
...
dataGrid1.ItemSource = devices;
}
public class Device : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public Device() {log = new ObservableCollection<string>();}
...
private ObservableCollection<string> _log;
public ObservableCollection<string> log { get { return _log; }
set { _log = value; OnPropertyChanged("log"); } }
}
你能分享任何建议吗:我如何在数据网格的每个组合框中显示每个对象的“日志”列表?
最佳答案
MSDN: DataGridComboboxColumns说:
To populate the drop-down list, first set the ItemsSource property for the ComboBox by using one of the following options:
- A static resource. For more information, see StaticResource Markup Extension.
- An x:Static code entity. For more information, see x:Static Markup Extension.
- An inline collection of ComboBoxItem types.
所以基本上只要绑定(bind)到数据对象的集合属性,最好使用 DataGridTemplateColumn
:
<DataGridTemplateColumn Header="Log">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding log}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
这种类型的列也为您提供了更多的模板化可能性。
关于wpf - 将 ComboBoxColumn 绑定(bind)到 WPF DataGrid 中 DataGrid 的 ItemsSource 的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17565236/