Home > Back-end >  Access a previous sibling element using RelativeSource binding (not ElementName) in WPF Application?
Access a previous sibling element using RelativeSource binding (not ElementName) in WPF Application?

Time:01-17

I am trying to access a property of a sibling element that comes directly BEFORE the target element. This is something I will have to duplicate several times in my app so I'd rather use something reproduceable (not elementName) if possible.

Any Ideas?

<Groupbox x:Name="GB1">

  <Checkbox x:Name="CB1" IsChecked="True"/>

  <TextBlock>
    <Style TargetType="TextBlock">
      <Style.Triggers>

        <Data.Trigger Binding RelativeSource={??? (I want this to access the Checkbox CB1 above), Path=IsChecked}" Value="True>
            <Setter Property="*Do a Thing if IsChecked=True*" Value="..."/>

      </Style.Triggers>
    </Style>
  </TextBlock>
</Groupbox>

CodePudding user response:

Maybe this example will give you an idea.

<StackPanel>
<TextBlock x:Name="textBlock1" Text="Text" />
<TextBlock x:Name="textBlock2" Text="Text">
    <TextBlock.Style>
        <Style TargetType="TextBlock">
            <Setter Property="Text" Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type StackPanel}}, Path=Children[0].Text}"/>
        </Style>
    </TextBlock.Style>
</TextBlock>
</StackPanel>

Path=Children[0].Text it will look for the first child element of this ancestor and access its Text property.

  • Related