1
我的DataGridComboBoxColumn不显示任何数据。它是空的。 我没有问题来填充组合框,但DataGridComboBoxColumn不起作用。
.NetFramework 4.6.1DataGridComboBoxColumn为空
型号:
public class Address
{
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Country { get; set; }
}
视图模型:
public class AddressViewModel
{
public AddressViewModel()
{
LoadAdresses();
LoadCountries();
}
public List<Address> AddressList { get; set; }
public List<string> CountryList { get; set; }
private void LoadAdresses()
{
AddressList = new List<Model.Address>();
AddressList.Add(new Model.Address(){ Firstname = "Peter", Lastname = "R.", Country = "A" });
AddressList.Add(new Model.Address(){ Firstname = "Tom", Lastname = "A.", Country = "A" });
AddressList.Add(new Model.Address(){ Firstname = "Sam", Lastname = "F.", Country = "A" });
}
private void LoadCountries()
{
CountryList = new List<string>();
CountryList.Add("A");
CountryList.Add("D");
CountryList.Add("CH");
CountryList.Add("GB");
CountryList.Add("F");
}
}
查看:
<Window.DataContext>
<vm:AddressViewModel/>
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<DataGrid x:Name="AddressDataGrid" Grid.Row="0" ItemsSource="{Binding AddressList}" AutoGenerateColumns="False" >
<DataGrid.Columns>
<DataGridTextColumn Header="Firstname" Binding="{Binding Firstname}" />
<DataGridTextColumn Header="Lastname" Binding="{Binding Lastname}" />
<DataGridComboBoxColumn Header="Country"
SelectedItemBinding="{Binding Country}"
ItemsSource="{Binding CountryList}"/>
</DataGrid.Columns>
</DataGrid>
<!--This ComboBox works-->
<ComboBox Grid.Row="1" ItemsSource="{Binding CountryList}"/>
</Grid>
什么是这种现象的原因?
我的DataGrid绑定到列表
AddressList的实例。类地址有一个属性国家。 DataGridComboBoxColumn绑定到此属性,并使用ListStyle其他组合框工作! – PeRa
我知道了,我已经看到你的代码:) 我试图解释为什么你的DataGridComboBox不起作用。这是因为你没有在正确的DataContext中。每行都有一个Address对象作为DataContext,并且在Address对象中没有CountryList。这就是为什么它不起作用。 DataGrid外部的ComboBox具有不同的DataContext。你有没有试过我的xaml代码? –
谢谢。你的xaml工作,我理解你的解释。非常复杂。这意味着,如果我想使用ItemsSource属性,我必须使用StaticResource? – PeRa