我想在代码中完全执行此操作,而不是XAML: 鉴于
DataGridComboBoxColumn myDGCBC = new DataGridComboBoxColumn();
ObservableCollection<string> DataSource = new ObservableCollection<string>{"Option1", "Option2"};
myDGCBC.ItemsSource = DataSource;
ObservableCollection<MyStructure> MyObject = new ObservableCollection<MyStructure>;
和
public class MyStructure
{
... several properties ... // pseudocode, obviously
public string SelectedValue { get; set; }
}
我感兴趣的是(绑定)从列中的所有comboxbox接收选定的值到SelectedValue
属性。
我从SO尝试了几个想法,但无济于事。
帮助! 感谢。
答案 0 :(得分:2)
假设已在xaml中定义了DataGird
,您应该为DataGrid
和DataGridComboBoxColumn
设置正确的绑定。
这是一个给你一个想法的例子:
<强>的Xaml:强>
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<DataGrid x:Name="myGrid" AutoGenerateColumns="False"/>
<Button Grid.Row="1" Content="test" Click="Button_Click"/>
</Grid>
<强> MainWindow.cs:强>
//DataGrid ItemsSource
public ObservableCollection<MyStructure> DataSource { get; set; }
public MainWindow()
{
InitializeComponent();
DataContext = this;
// Initializing DataGrid.ItemsSource
DataSource = new ObservableCollection<MyStructure>();
DataSource.Add(new MyStructure());
// Creating new DataGridComboBoxColumn
DataGridComboBoxColumn myDGCBC = new DataGridComboBoxColumn();
myDGCBC.Header = "cmbColumn";
// Binding DataGridComboBoxColumn.ItemsSource and DataGridComboBoxColumn.SelectedItem
var cmbItems = new ObservableCollection<string> { "Option1", "Option2" };
myDGCBC.ItemsSource = cmbItems;
myDGCBC.SelectedItemBinding = new Binding("SelectedValue");
// Adding DataGridComboBoxColumn to the DataGrid
myGrid.Columns.Add(myDGCBC);
// Binding DataGrid.ItemsSource
Binding binding = new Binding();
binding.Source = DataSource;
BindingOperations.SetBinding(myGrid, DataGrid.ItemsSourceProperty, binding);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
//This is just to check whether SelectedValue is set properly:
string selectedValue = DataSource[0].SelectedValue;
}