我不知道你如何在 ColumnHeader 中获得 Combobox,但我假设是通过 ColumnHeaderStyle,所以我的方法是将 SelectedValueProperty 绑定到 CodeBehind 或 ViewModel 中的属性
<ComboBox x:Name="headerComboBox" ItemsSource="{Binding Path=headerSource}">
<ComboBox.SelectedValue>
<Binding Path="HeaderSelectedValue" Mode="TwoWay" />
</ComboBox.SelectedValue>
编辑:
C# 解决方案(未测试)
foreach (var column in myGrid.Columns)
{
var colHeader = (DependencyObject)column.Header;
var headerComboBox = colHeader.GetChildOfType<ComboBox>();
var selected = headerComboBox.SelectedValue.ToString();
}
这是 ExtensionMethod GetChildOfType
public static T GetChildOfType<T>(this DependencyObject depObj) where T : DependencyObject
{
if (depObj == null) return null;
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
var child = VisualTreeHelper.GetChild(depObj, i);
var result = (child as T) ?? GetChildOfType<T>(child);
if (result != null) return result;
}
return null;
}
编辑 2:如果你像这样定义 ColumnHeader
<DataGridTextColumn Width="250">
<DataGridTextColumn.Header>
<ComboBox Width="200">
<ComboBox.Items>
<ComboBoxItem Content="Test1"/>
<ComboBoxItem Content="Test2"/>
</ComboBox.Items>
</ComboBox>
</DataGridTextColumn.Header>
</DataGridTextColumn>
然后 column.Header 实际上是组合框,因此无需向下查看可视树,您只需将其转换为组合框
var colHeader = (Combobox)column.Header;
也许您可以告诉我如何在列标题中定义组合框