Saturday, February 19, 2011

WPF: Problem with binding values to ComboBox inside GridViewColumn

My Views dataContext is bounded to a presentationModel with two observableCollections Members. In the View I have one listView which ItemSource is bound to is the first observableCollection. In one of the LilstViews column I want to present values from the second obeservable Colletion in my presentationModel. I cant figure out how to get the values from the observableCollection into my combobox. Does anyone have an idea how to solve this problem?

From stackoverflow
  • First thing you need to do is create a data template containing your ComboBox, in this case I have bound the ItemsSource to a DependencyProperty on the host Window. This contains the presentation model, which has a property called ComboSource. SelectedValue has been bound, via the ListViewItem's DataContext, to a property which holds the selected value.

    <ListView.Resources>
        <DataTemplate x:Key="comboBoxTemplate">
            <ComboBox
                ItemsSource="{Binding 
                                Path=ModelData.ComboSource, 
                                RelativeSource={RelativeSource AncestorType=Window}}"
                SelectedValue="{Binding 
                                Path=DataContext.Selection, 
                                RelativeSource={RelativeSource AncestorType=ListViewItem}}"
                DisplayMemberPath="Item"
                SelectedValuePath="Id"
                />
        </DataTemplate>
    </ListView.Resources>
    

    Then you will need to reference this from the CellTemplate on the GridViewColumn

    <GridViewColumn
        Header="Selection"
        Width="160"
        CellTemplate="{StaticResource comboBoxTemplate}"
        />
    
    KaJo : Tanks!!! This was very helpful
  • I can't get this sample to work. It would be a great help if you could post sample code for download or tell me where to get something similar.

    Thanks, Dan

0 comments:

Post a Comment