Search code examples
silverlightxamlrelativesource

Reaching up the tree via RelativeSource and FindAncestor to change dependency properties


Looking to learn something new today and hoping someone has an elegant way of accomplishing this in just XAML.

So for the concept take the following example;

<Grid>

   <ScrollViewer VerticalScrollbarVisibility="Auto">

      <Grid>
         <Grid.Resources>
           <Style TargetType="{RelativeSource Mode=FindAncestor, AncestorType=ScrollViewer}">
              <Setter Property="VerticalScrollbarVisibility" Value="Disabled"/>
           </Style>
         </Grid.Resources>
      </Grid>

   </ScrollViewer>

</Grid>

Which obviously won't work (nor was expected too), but... it conveys the concept fo what I'd like to accomplish. Reaching up the tree to manipulate an Ancestors Dependencies at runtime without being able to target an element directly even if they're potentially in separate UserControl's being brought together in one view.

I tried throwing a Storyboard at a Loaded event to change the properties with a DoubleAnimation and some other attempts but no joy so far which is understandable but it's all just in the name of improving the skillset anyway. I'm trying to accomplish it purely with XAML and I'm confident it's just one of those things another pair of eyes could provide a different route.


Solution

  • I'm not sure why your storyboard approach wouldn't work (could it be because of the typo in VerticalScroll B arVisibility?.

    A variation on that approach would be to use a ChangePropertyAction inside the Loaded event. I can confirm this works to disable the scroll bar:

      <Grid>
         <i:Interaction.Triggers>
             <i:EventTrigger EventName="Loaded">
                 <ei:ChangePropertyAction 
                     TargetObject="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ScrollViewer}}"
                     PropertyName="VerticalScrollBarVisibility"
                     Value="Disabled"
                 />
             </i:EventTrigger>
         </i:Interaction.Triggers>
      </Grid>