Reputation: 1005
I'm trying to get a dropdown column in a WPF datagrid (hosted in a user control derived from a base class called ControlBase) to bind properly. It initially populates fine from the object, and a populated dropdown appears when I edit the cell, but a selected value does not get back into the cell when I leave focus.
Here's my model and domain objects:
public class ModelBase : INotifyPropertyChanged
{
public IList<Person> Persons { get; set; }
}
public class UserControlModel : ModelBase
{
public ObservableCollection<DatagridRecord> SourceData { get; set; }
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
public class DatagridRecord
{
public string Name { get; set; }
public Person ContactPerson { get; set; }
}
And in my xaml.cs, I set the DataContext via a Model property:
public UserControlModel _model;
public UserControlModel Model
{
set
{
_model = value;
DataContext = null;
DataContext = _model;
}
}
Here's my DataGrid column definition in xaml:
<DataGridTemplateColumn Header="Person" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=ContactPerson.Name}"/></DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Path=DataContext.Persons,
RelativeSource={RelativeSource AncestorType={x:Type uch:ControlBase}}}"
DisplayMemberPath="Name"
SelectedValuePath="Id" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
I figure there is something wrong with tying the combobox selected value to the grid row, but I've gone around in circles trying to hook it up. Any advice would be appreciated.
Corey.
Upvotes: 1
Views: 3436
Reputation: 44028
You're Missing a SelectedItem
or SelectedValue
binding:
<ComboBox ItemsSource="{Binding Path=DataContext.Persons,
RelativeSource={RelativeSource AncestorType={x:Type uch:ControlBase}}}"
DisplayMemberPath="Name"
--> SelectedItem="{Binding ContactPerson}" <--
SelectedValuePath="Id" />
Upvotes: 1