如果您不打扰其他演员,您可以这样做
for (int i = 0; i < dgResults.Items.Count; i++)
{
var x = dgResults.GetCell(i, 0).Content as System.Windows.Controls.ComboBox;
var array = x.ItemsSource as string[] ;
x.SelectedItem = array.Where(s => s == "B").FirstOrDefault();
}
编辑:好的,现在应该可以了
工作样本:
XAML
<Window x:Class="simpletest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<x:Array x:Key="ReminderValues" Type="sys:String">
<sys:String>A</sys:String>
<sys:String>B</sys:String>
<sys:String>C</sys:String>
<sys:String>D</sys:String>
</x:Array>
<x:Array x:Key="count" Type="sys:String">
<sys:String>A</sys:String>
</x:Array>
</Window.Resources>
<Grid>
<DataGrid Name="dgResults" ItemsSource="{StaticResource count}" AutoGenerateColumns="False" >
<DataGrid.Columns>
<DataGridComboBoxColumn ItemsSource="{StaticResource ReminderValues }" />
</DataGrid.Columns>
</DataGrid>
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="428,12,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
</Grid>
</Window>
CS
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < dgResults.Items.Count; i++)
{
var x = dgResults.GetCell(i, 0).Content as System.Windows.Controls.ComboBox;
var array = x.ItemsSource as string[];
x.SelectedItem = array.Where(s => s == "B").FirstOrDefault();
}
}
}