I
I
Igor Antonik2015-05-31 16:47:10
WPF
Igor Antonik, 2015-05-31 16:47:10

How to bind an element using RelativeSource in WPF to another element of the same level?

I have a ListBox with the following item template:

<ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <CheckBox IsChecked="true"></CheckBox>
                        <Image Width="22"
                               Height="22"
                               Margin="5"
                               Source="/Images/play.png"
                             >
                            <Image.Style>
                                <Style>
                                    <Style.Triggers>
                                        <DataTrigger Binding="{Binding Path=IsChecked, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=CheckBox}}" Value="true">
                                            <Setter Property="Image.Source" Value="/Images/pause.png"/>
                                        </DataTrigger>
                                        <DataTrigger Binding="{Binding Path=IsChecked, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=CheckBox}}" Value="false">
                                            <Setter Property="Image.Source" Value="/Images/play.png"/>
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </Image.Style>
                        </Image>

                        <StackPanel>
                            <TextBlock FontWeight="Bold" Text="{Binding Path=title}"></TextBlock>
                            <TextBlock Text="{Binding Path=duration}" />
                        </StackPanel>

                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>

You need to bind the trigger that changes the image to the CheckBox's IsChecked property. Is it possible to do this? Now there is a binding to the parent element using FindAncestor.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
pupunussi, 2015-08-06
@Svjatogor

It's easiest to bind using x:Name and ElementName:
Further

<DataTrigger Binding="{Binding IsChecked, ElementName=CheckBox}" Value="False">
    ...
</DataTrigger>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question