wpf - 将 ComboBoxColumn 绑定(bind)到 WPF DataGrid 中 DataGrid 的 ItemsSource 的集合

标签 wpf binding datagrid combobox

请帮助我了解如何在 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/

相关文章:

wpf - WPF 中的切换按钮

C# WPF 应用程序在 VS 调试中运行,但不作为 EXE 运行

wpf - 将列表框项内的命令绑定(bind)到 View 模型父级上的属性

url - Http.sys URL 前缀注册如何转换为 IIS 绑定(bind)配置?

c# - 如何在具有许多绑定(bind)的巨大 View 中找到错误的绑定(bind)?

c# - 为什么 ContextMenu Command 和 CommandParameter 在 DataGrid 中不起作用

gwt - 使数据网格的行在 GWT 中可拖动

c# - WPF DataGrid 的 CollectionViewSource MVVM 实现

c# - 从数据网格中获取复选框的值?

wpf - 如何将 Illustrator 文件转换为 WPF 的路径