简体   繁体   English

将ComboBoxColumn绑定到WPF DataGrid中DataGrid的ItemsSource的集合

[英]Binding ComboBoxColumn to collection from DataGrid's ItemsSource in WPF DataGrid

Please help me to figure out how to work with ComboBoxColumn in WPF's DataGrid. 请帮助我弄清楚如何在WPF的DataGrid中使用ComboBoxColumn。 I'm trying to create a list of devices, where each device have dynamic list of states in field "log". 我正在尝试创建设备列表,其中每个设备在“ log”字段中都有动态状态列表。

<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"); } }
}

Can you share any suggestions: How can i show in each combobox in datagrid list "log" of each object? 您能否分享任何建议:如何在每个对象的数据网格列表“日志”中的每个组合框中显示?

MSDN: DataGridComboboxColumns says: MSDN:DataGridComboboxColumns说:

To populate the drop-down list, first set the ItemsSource property for the ComboBox by using one of the following options: 若要填充下拉列表,请首先使用以下选项之一设置ComboBox的ItemsSource属性:

  • A static resource. 静态资源。 For more information, see StaticResource Markup Extension. 有关更多信息,请参见StaticResource标记扩展。
  • An x:Static code entity. x:静态代码实体。 For more information, see x:Static Markup Extension. 有关更多信息,请参见x:静态标记扩展。
  • An inline collection of ComboBoxItem types. ComboBoxItem类型的嵌入式集合。

So basically to just bind to data object`s collection property it`s better to use DataGridTemplateColumn : 因此,基本上只绑定到数据对象的collection属性,最好使用DataGridTemplateColumn

<DataGridTemplateColumn Header="Log">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
             <ComboBox ItemsSource="{Binding log}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

This type of column gives you some more posibilities for templating too. 这种类型的列也为您提供了更多的模板可能性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM