I want to rotate the button when clicking. I thought that should work like this:

void new_button_click(object sender, RoutedEventArgs e) { Button btn = sender as Button; var transform = btn.RenderTransform as RotateTransform; transform.Angle += 90; } 

But it does not work)) What's wrong? I want to implement a rotation using C # code, not XAML. When clicking, swears at this line:

 transform.Angle += 90; 

An exception:

The object reference does not indicate an object instance.

    1 answer 1

    From your code it turns out that in this line:

     var transform = btn.RenderTransform as RotateTransform; 

    we get the value null , so we get an exception below. The link to the object does not indicate an object instance when accessing transform.Angle . Therefore, you should add a check, and then turn, try this:

     void new_button_click(object sender, RoutedEventArgs e) { Button btn = sender as Button; if(btn != null) { var rotateTransform = btn.RenderTransform as RotateTransform; var transform = new RotateTransform(90 + (rotateTransform?.Angle ?? 0)); btn.RenderTransform = transform; } } 

    In this example, the button is rotated 90 degrees after each press.

    Useful links:

    1. Transforms Overview
    2. UIElement.RenderTransform Property
    3. How to: Rotate an Object
    • Thanks a lot for your help! Turned, but only once: when pressed again, nothing happens. I would like to rotate with each click, tell me, please, how to implement it? - Saint
    • one
      @Saint to change more (less) change the value inside the RotateTransform constructor to the one you need - Denis Bubnov
    • and this is another question: how to make a rotation relative to the center? And then if you expand to 180, then the button generally turns in the other direction. That is, as I understand it, the turn is now carried out relative to the left upper edge of the button. - Saint
    • one
      @Saint, the Practical Guide is written here in sufficient detail . Rotation of the object , you need to set the center of rotation. - Denis Bubnov
    • @Saint, so you need to increase the angle. And all the time you are writing the same corner, here it is, and it stands. Open the third link in the answer, in the comments I attached the same one, only in Russian. Now I will give a link. - Denis Bubnov