Search code examples
wpfdatagriddependenciesexpander

wpf - how can I create a dependency between expander inside datagrid and one of datagridrow properties


This is a general question. And may not be specific to datagrids. How can i related 2 properties or 2 different UI Elements/controls

Like Each datagridRow has an Expander and i want the IsExpanded property to be dependent on datagridrow selected event .

Thank you


Solution

  • A relative source binding can be used to bind two properties without referring to the source element by name. This is especially useful is styles.

    Here's an example of a ListBox with items that expand when selected.

    <ListBox>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Expander
                    Header="{Binding}"
                    IsExpanded="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListBoxItem}, Path=IsSelected}">
                    <TextBlock
                        Text="{Binding}" />
                </Expander>
            </DataTemplate>
        </ListBox.ItemTemplate>
    
        <sys:String>a</sys:String>
        <sys:String>b</sys:String>
        <sys:String>c</sys:String>
        <sys:String>d</sys:String>
    
    </ListBox>
    

    When I need a fancy binding, I regularly use a cheat sheet posted by Nir on his blog and referenced in the StackOverflow question Is there a WPF Cheat Sheet outhere?.

    Here's the cheat sheet direct link.

    If you ever read this, thanks Nir.