0

Is there a more elegant way to change a single element in a View.Frame struct in Xamarin/C# without using one of the following patterns?

var frame = View.Frame;
frame.Y = 123;
View.Frame = frame;

or

View.Frame = new RectangleF(View.Frame.X, 123, View.Frame.Width, View.Frame.Height);

Simply changing the element like this: View.Frame.Y = 123; doesn't have any effect. Only once the entire Frame struct is reassigned does it take effect.

It'sNotALie.
  • 22,289
  • 12
  • 68
  • 103
Jason Hartley
  • 2,459
  • 1
  • 31
  • 40
  • 1
    It probably doesn't have any effect because `View.Frame` is probably a property. When you access it, it returns a _copy_ of the Frame because it's a value type. I personally prefer your first style; seems a bit more explicit about what your intent is regarding what aspects are changing. (not to mention it avoids hitting the `Frame` property getter 3 times) – Chris Sinclair May 11 '13 at 23:29

1 Answers1

1

I took a few minutes and tried to come up with something, but because the Frame is a struct it doesn't look there is a more elegant way:

MonoTouch: How to change control's location at runtime?

One thing you could possibly do is create a static utility class like this that you could reuse:

public static class FrameUtil{
     public RectangleF UpdateX(RectangleF frame, float newX){
          var tempFrame = frame;
          tempFrame.x = newX;
          return tempFrame;
     }
}
Community
  • 1
  • 1
Ben Bishop
  • 1,414
  • 9
  • 14
  • `View.Frame = new RectangleF(View.Frame.X, 123, View.Frame.Width, View.Frame.Height);` is now: `View.Frame = FrameHelper.X(View.Frame, 123);` This is a little better. I've already started using it. Thanks. – Jason Hartley May 13 '13 at 02:44