Meine DataGridComboBoxColumn zeigt keine Daten an. Es ist leer. Ich habe kein Problem, eine ComboBox zu füllen, aber DataGridComboBoxColumn funktioniert nicht.
.NetFramework 4.6.1DataGridComboBoxColumn ist leer
Modell:
public class Address
{
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Country { get; set; }
}
Ansichtsmodell:
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");
}
}
Ausblick:
<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>
Was ist der Grund für dieses Verhalten?
Mein DataGrid ist an eine Instanz der Liste
AddressList gebunden. Die Klasse Adresse hat eine Eigenschaft Land. Die DataGridComboBoxColumn ist an diese Eigenschaft gebunden und verwendet eine Instanz von ListDas andere Kombinationsfeld funktioniert! – PeRa
Ich weiß, ich habe Ihren Code gesehen :) Und ich habe versucht zu erklären, warum Ihre DataGridComboBox nicht funktioniert. Es liegt daran, dass Sie nicht im richtigen DataContext sind. Jede Zeile hat ein Address-Objekt als DataContext und es gibt keine CountryList in Ihrem Address-Objekt. Deshalb funktioniert es nicht. Die ComboBox außerhalb des DataGrid hat einen anderen DataContext. Hast du meinen XAML-Code ausprobiert? –
Danke. Dein Xaml funktioniert und ich verstehe deine Erklärung. Ziemlich kompliziert. Das heißt, wenn ich die ItemsSource-Eigenschaft verwenden möchte, muss ich mit einer StaticResource arbeiten? – PeRa