I have a DataGrid
which displays a list of objects. One of the properties in the objects is another custom object. This object is shown as a ComboBox
in the grid. When I change the selected item in the ComboBox
from the grid, everything seems to work as I expect. However, when I change the selected item from code behind, the SelectedItem
in the ComboBox
doesn't update. I have implemented the INotifyPropertyChanged
and the event is firing as it should. I have also tried to print the domain name in a TextBox
and it shows the correct value. The problem I have is that the SelectedItemBinding
doesn't seem to work when I update from code behind. Can anyone explain why? Here is my code:
XAML
<DataGrid AutoGenerateColumns="False" Height="506" HorizontalAlignment="Left" Name="EntityGrid" VerticalAlignment="Top" Width="360" Margin="10,62,0,0">
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridCell}">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="DataGridCell_PreviewMouseLeftButtonDown" />
<EventSetter Event="PreviewTextInput" Handler="DataGridCell_PreviewTextInput" />
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding dbName, Mode=TwoWay}" />
<DataGridComboBoxColumn x:Name="Domain" Header="Domain" SelectedItemBinding="{Binding Domain, Mode=TwoWay}" DisplayMemberPath="DomainName}"/>
<DataGridCheckBoxColumn Header="Static" Binding="{Binding Static}" IsReadOnly="True" />
</DataGrid.Columns>
</DataGrid>
My objects
public class Entity : INotifyPropertyChanged
{
private string _dbName;
public string dbName { get { return _dbName; } set { _dbName = value; NotifyPropertyChanged("dbName"); } }
public string EntityName { get; set; }
private Domain _domain;
public Domain Domain
{
get { return _domain; }
set
{
_domain = value;
NotifyPropertyChanged("Domain");
}
}
public bool Static { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public class Domain : INotifyPropertyChanged
{
public string DomainName { get; set; }
public string ContextName { get; set; }
public string FileName { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Init code
List<Domain> domains = getDomainsFromConfig();
List<Entity> Entities = dal.getAllEntities(config.Paths.dbml.AllEntities, config.Paths.dbml.LockedEntities);
EntityGrid.ItemsSource = Entities;
Domain.ItemsSource = domains;
Update code
foreach (Entity entity in Entities)
{
entity.Domain = getDefaultDomain();
}