绑定ComboBoxColumn到从DataGrid的ItemsSource在WPF DataGrid中的集合 [英] Binding ComboBoxColumn to collection from DataGrid's ItemsSource in WPF DataGrid
问题描述
请帮助我找出如何使用ComboBoxColumn在WPF的DataGrid。
我试图创建一个设备列表,其中每个设备都有log字段的动态状态列表。
Please help me to figure out how to work with ComboBoxColumn in WPF's DataGrid. I'm trying to create a list of devices, where each device have dynamic list of states in field "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"); } }
}
您可以分享任何建议:如何在每个组合框中显示datagrid listlogof each object?
Can you share any suggestions: How can i show in each combobox in datagrid list "log" of each object?
推荐答案
MSDN:DataGridComboboxColumns 说:
要填充下拉列表,首先使用以下选项之一为
ComboBox设置ItemsSource属性:
To populate the drop-down list, first set the ItemsSource property for the ComboBox by using one of the following options:
- 静态资源。有关详细信息,请参阅StaticResource标记扩展。
- x:静态代码实体。有关详情,请参阅x:静态标记扩展。
- ComboBoxItem类型的内联集合。
所以基本上只是绑定到数据对象的collection属性,最好使用 DataGridTemplateColumn
:
So basically to just bind to data object`s collection property it`s better to use 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.
这篇关于绑定ComboBoxColumn到从DataGrid的ItemsSource在WPF DataGrid中的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!