how to use RelativeSource to populate DataGridComboBoxColumn when DataContext set at Window/UserControl

Mar 24, 2009 at 9:52 PM
Edited Mar 26, 2009 at 8:46 PM
I'm using an MVP pattern and am using a model to set the datacontext for my View.

This model has three attributes (pseudocode)
Model
{
ObservableCollection<employee> Employees
ObservableCollection<status> StatusList
bool isViewEditable
}

The ItemsSource for my dataGrid is set to Employees.  I can bind the attributes of the employee to columns of the grid successfully.

Next, I need to supply the ItemsSource for a DataGridComboBox.  I've trying to use RelativeSoure with the binding to "crawl back up".

      <my:DataGrid    
             CanUserAddRows="False" 
             Name="DataGridEmployees" 
             ItemsSource="{Binding Path=Employees}"             
             AutoGenerateColumns="False">            
           <my:DataGrid.Columns>
                <my:DataGridTextColumn Binding="{Binding Path=ID}" Header="ID" />
                <my:DataGridTextColumn Binding="{Binding Path=Name}" Header="Name" />
<!-- The following won't work since Status is not an attribute of Employees -->
                <!--<my:DataGridComboBoxColumn   ItemsSource="{Binding Path= StatusList}" Header="Status"/>-->  
               
<!-- The Path and the Ancestor Level are -->
               <my:DataGridComboBoxColumn
                    ItemsSource="{Binding
                   RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, Path=DataContext}"
              />               
            </my:DataGrid.Columns>
        </my:DataGrid.>

How can I accomplish this? 

(NOTE: in my main application, the views are usercontrols however, I am testing with a simple window) 

ManyThanks!
Coordinator
Mar 26, 2009 at 9:34 PM
Edited Mar 26, 2009 at 9:34 PM
The following should work...
               <my:DataGridComboBoxColumn Header="Status" SelectedItemBinding=...>
                    <my:DataGridComboBoxColumn.ElementStyle>
                        <Style TargetType="{x:Type ComboBox}">
                            <Setter Property="ItemsSource" Value="{Binding Path=DataContext.StatusList, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
                        </Style>
                    </my:DataGridComboBoxColumn.ElementStyle>
                    <my:DataGridComboBoxColumn.EditingElementStyle>
                        <Style TargetType="{x:Type ComboBox}">
                            <Setter Property="ItemsSource" Value="{Binding Path=DataContext.StatusList, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
                        </Style>
                    </my:DataGridComboBoxColumn.EditingElementStyle>
                </my:DataGridComboBoxColumn>