Handle Expanded
event and call BringIntoView()
method:
private void Expander_Expanded(object sender, RoutedEventArgs e)
{
((Expander)sender).BringIntoView();
}
Please note that you should use StackPanel or something else instead of Grid
:
<ScrollViewer Name="sv">
<UserControl>
<StackPanel>
<Expander>
<Border Height="1000" Background="Red"/>
</Expander>
<Expander>
<Border Height="1000" Background="Blue"/>
</Expander>
<Expander Expanded="Expander_Expanded">
<Border Height="1000" Background="Green"/>
</Expander>
</StackPanel>
</UserControl>
</ScrollViewer>
Edit
You might want to use this attached property:
public static class ExpanderEx
{
public static readonly DependencyProperty BringIntoViewOnExpandProperty =
DependencyProperty.RegisterAttached("BringIntoViewOnExpand",
typeof(bool), typeof(ExpanderEx),
new PropertyMetadata(false, OnBringIntoViewOnExpandChanged));
public static bool GetBringIntoViewOnExpand(DependencyObject obj)
{
return (bool)obj.GetValue(BringIntoViewOnExpandProperty);
}
public static void SetBringIntoViewOnExpand(DependencyObject obj, bool value)
{
obj.SetValue(BringIntoViewOnExpandProperty, value);
}
private static void OnBringIntoViewOnExpandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is Expander)
{
Expander obj = (Expander)d;
if (e.NewValue.Equals(true))
obj.Expanded += Obj_Expanded;
else
obj.Expanded -= Obj_Expanded;
}
}
private static void Obj_Expanded(object sender, RoutedEventArgs e)
{
((Expander)sender).BringIntoView();
}
}
and in Xaml:
<ScrollViewer Name="sv">
<UserControl>
<StackPanel>
<Expander local:ExpanderEx.BringIntoViewOnExpand="True">
<Border Height="1000" Background="Red"/>
</Expander>
<Expander local:ExpanderEx.BringIntoViewOnExpand="True">
<Border Height="1000" Background="Blue"/>
</Expander>
<Expander local:ExpanderEx.BringIntoViewOnExpand="True">
<Border Height="1000" Background="Green"/>
</Expander>
</StackPanel>
</UserControl>
</ScrollViewer>