Note that there are some explanatory texts on larger screens.

plurals
  1. POWPF DataGridTemplateColumn with ComboBox Binding (MVVM pattern)
    primarykey
    data
    text
    <p>I'm going bonkers with the following WPF DataGrid+ComboBox scenario.</p> <p>I have a set of classes which look like;</p> <pre><code>class Owner { int ID { get; } string Name { get; } public override ToString() { return this.Name; } } class House { int ID { get; } Owner HouseOwner { get; set; } } class ViewModel { ObservableCollection&lt;Owner&gt; Owners; ObservableCollection&lt;House&gt; Houses } </code></pre> <p>Now my desired outcome is a DataGrid which shows a list of rows of type <strong>House</strong>, and in one of the columns, is a ComboBox which allows the user to change the value of <strong>House.HouseOwner</strong>. </p> <p>In this scenario, the DataContext for the grid is <strong>ViewModel.Houses</strong> and for the ComboBox, I want the ItemsSource to be bound to ViewModel.Owners.</p> <p>Is this even possible? I'm going mental with this... the best I've been able to do is to correctly get the ItemsSource bound, however the ComboBox (inside a DataGridTemplateColumn) is not showing the correct values for House.HouseOwner in each row.</p> <p>NOTE: If I take the ComboBox out of the picture and put a TextBlock in the DataTemplate instead, I can correctly see the values for each row, but getting both an ItemsSource as well as show the correct value in the selection is not working for me...</p> <p>Inside my code behind, I have set the DataContext on the Window to <strong>ViewModel</strong> and on the grid, the DataContext is set to <strong>ViewModel.Houses</strong>. For everything except this combobox, it's working...</p> <p>My XAML for the offending column looks like;</p> <pre><code>&lt;DataGridTemplateColumn Header="HouseOwner"&gt; &lt;DataGridTemplateColumn.CellTemplate&gt; &lt;DataTemplate&gt; &lt;ComboBox ItemsSource="{Binding Path=DataContext.Owners, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" DisplayMemberPath="Name" SelectedItem="{Binding HouseOwner, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" SelectedValue="{Binding HouseOwner.ID, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, Mode=OneWay}" SelectedValuePath="ID" /&gt; &lt;/DataTemplate&gt; &lt;/DataGridTemplateColumn.CellTemplate&gt; &lt;/DataGridTemplateColumn&gt; </code></pre> <p>Would love some help on this one... seems like a bit of Voodoo is required though...</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload