0

I am writing a custom XAML control with several visual states. I am able to change visual states in the control's code behind, however I am not able to retrieve the current state.

I tried this solution, which looked very good.

Silverlight: VisualStateManager.GetVisualStateGroups doesn't, How can I get them?

However it throws an internal exception, not enough to crash the app, but my IList does not exist. I think the exception occurs because this fails to return anything valid VisualTreeHelper.GetChild(this, 0) as FrameworkElement);

How can I get the visual state of a control from within the code of the control itself.

Xaml code:

<Style TargetType="cc:MyControl" >
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="cc:MyControl">
        <Canvas x:Name="MyControlCanvas" Width="17" Height="43" HorizontalAlignment="Left" VerticalAlignment="Top">
          <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="MyControlStateGroup" >
              <VisualState x:Name="Normal">
                <VisualState.Setters>
                  <Setter Target="rectangle_Copy1.(UIElement.Opacity)" Value="1"/>
Community
  • 1
  • 1
TheBard
  • 156
  • 1
  • 11
  • Is the VisualStateManager the first element under the first child element of the control? Can we see a bit of XAML your control uses? – Igor Ralic Nov 07 '15 at 15:09
  • http://pastebin.com/1Uy5vAG2 this shows the upper part of the control xaml code. – TheBard Nov 07 '15 at 15:15
  • Does this return anything: VisualTreeHelper.GetChild(this, 0)? – Igor Ralic Nov 07 '15 at 15:22
  • @jockey4her Where do you call `VisualTreeHelper.GetChild(this, 0)`? The element should be in visual tree, otherwise I think you can get null/no elements. – Romasz Nov 07 '15 at 15:27
  • I got it to work just now, but to be honest, I'm not exactly sure why.. When if failed, I had called it from a DispatcherTimer tick. When it worked, I first called it from: protected override void OnApplyTemplate() – TheBard Nov 07 '15 at 15:33
  • @jockey4her Yeah, that's because the template wasn't applied before that tick. It has to be in order to get the template elements. – Igor Ralic Nov 07 '15 at 15:37
  • Yes. There is a definite order of operations. What I did was to hold all 'in control' timers and start them in OnApplyTemplate. Then when the tickers finish the initializations, set a 'done flag'. In the ViewModel, watch for the done flag, then and only then, create model instances that rely on the control being fully initialized. Tricky, and not that obvious when I started writing the control. But it makes for a very responsive control in the end. – TheBard Nov 10 '15 at 13:11

0 Answers0