Using declarative style C# instead of XAML - should Xamarin redirect XAML efforts elsewhere?

VincentHVincentH USBeta ✭✭

Introduction

Miguel tweeted:
"I should have never added Xaml and instead invented our own ...", expressing regrets about having to deal with XAML (standardization) problems.

My response was:
"I would applaud dropping XAML altogether. Advancements in C# (declarative syntax) have eliminated any advantages of a separate markup language for years. Why would you want to hand-code an object serialization format? Why waste time on duplicating dev tools for features that c# already offers?"

David expressed an interest to see how I have been creating Xamarin Forms markup in declarative style C#, instead of in XAML, for the past few years. So I write this post to provide a concrete example, and share the reasoning behind my remark (which was deliberately lacking nuance - it is Twitter after all).

Redirecting Xamarin IDE team effort

Why do I spend time on this? In the past years I only experienced advantages from using declarative C# instead of XAML. Given that the core challenge for the Xamarin IDE teams remains to improve the developer productivity, I would love to see some of the effort now being spent on (imo redundant) XAML tooling to be redirected towards reducing IDE bugs and speeding up the dev cycle, i.e. Live Player.

I recently investigated Google's Flutter (build beautiful native apps in record time), which by design has no separate language for markup and which offers hot reload - which is like a Xamarin Live Player without any limitations and a refresh time of 400-600 ms (I checked on devices and emulators). This is what I want from Xamarin!

This is the competition Xamarin is facing today. Some developers are already switching from Xamarin to Flutter because of developer tooling productivity, which apparently can be more important than language or framework or experience. As a Xamarin veteran, I get why they do this. I feel that unless there is a significant team increase, Xamarin needs to focus and redirect existing effort towards developer productivity, meaning less IDE bugs and faster development cycle.

Example
.
Here is an unabridged example of a simple registration code page in a production app I wrote:

Content = new Grid { 
    RowSpacing = 0, 
    RowDefinitions = { new RowDefinition { Height = GridLength.Auto }, new RowDefinition {}},
    Children = {
        PageHeader.Create(PageMarginSize, nameof(vm.RegistrationTitle), returnToPreviousViewCommandPropertyName: nameof(vm.CancelEnterRegistrationCodeCommand), centerTitle:true),

        new ScrollView { Content = new Grid {
            RowDefinitions = {
                new RowDefinition { Height = 170 },

                new RowDefinition { Height = 75 },
                new RowDefinition { Height = GridLength.Auto },
                new RowDefinition { Height = GridLength.Auto }
            },
            RowSpacing = 0,

            ColumnDefinitions = {
                new ColumnDefinition { Width = 160 },
                new ColumnDefinition { }
            },

            Children = {
                new Label {
                    Margin = fieldNameMargin, LineBreakMode = LineBreakMode.WordWrap, 
                    HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.Center, HorizontalTextAlignment = TextAlignment.Center, 
                }.SetFontSize(WspFontSizes.Size15)
                 .SetColRow(0, 2, 0, 1)
                 .Bind(nameof(vm.RegistrationPrompt)),

                new Label { Text = "Registration code", VerticalOptions = LayoutOptions.End, Margin = fieldNameMargin }.SetFontSize(WspFontSizes.Size13)
                .SetColRow(0, 1, 1, 2),
                new Label { HorizontalOptions = LayoutOptions.End, VerticalOptions = LayoutOptions.End, Margin = fieldNameMargin }.SetFontSize(WspFontSizes.Size13)
                .SetColRow(1, 2, 1, 2)
                .Bind(nameof(vm.RegistrationCodeValidationMessage)),

                new Entry {
                    Placeholder = "E.g. 123456", HeightRequest = 44, Keyboard = Keyboard.Numeric, 
                    BackgroundColor = WspColors.White.ToColor(), TextColor = WspColors.Gray1.ToColor(), Margin = fieldMargin }.SetFontSize(WspFontSizes.Size15)
                .Bind(nameof(vm.RegistrationCode), BindingMode.TwoWay)
                .Id(AId.RegistrationCodePage_CodeEntry)
                .SetColRow(0, 2, 2, 3),

                new Button {
                    Text = "Verify",
                    Margin = PageMarginSize,
                    HeightRequest = 44,
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    TextColor = WspColors.White.ToColor(),
                    BackgroundColor = WspColors.ColorValueAccent.ToColor()
                }.SetFontSize(WspFontSizes.Size13)
                 .Id(AId.RegistrationCodePage_VerifyCodeButton)
                 .Bind(Button.IsVisibleProperty, nameof(vm.CanVerifyRegistrationCode))
                 .Bind(nameof(vm.VerifyRegistrationCodeCommand))
                 .SetColRow(0, 2, 3, 4),
            }
        }}.SetColRow(0, 1)
     }
 };

Nothing advanced is going on here, I use standard C# language features to reuse controls (e.g. PageHeader.Create method ) and to simplify data binding (.Bind extension methods). In my eyes the above reads similar to equivalent XAML.

Which is not very surprising given that XAML is at its heart just an object serialization format in XML. In other words, XAML does what the new keyword in C# does.

Now, C# is designed for humans; while XML is better for tools such as visual designers. As a matter of fact, that was the vision for (WPF) XAML: that human designers could use a tool (Blend) to create a UI that developers could consume. However, I experienced how that vision, even in the best possible time and scenario, failed to deliver (I Built a WPF app for Windows tablet together with a XAML book authoring, leading designer, who was a master in Blend, when that was THE tool. The UI was beautiful and totally unmaintainable). So even if there would come an ultimate visual designer tool for Xamarin Forms, equivalent to the best that Blend ever was, it would still fail for the same reasons. Time to move on, like Flutter?

So, anyone (Xamarin devs and Xamarin team) wants to chime in on either XAML versus C# or redirecting Xamarin IDE efforts?
I'm really curious how Xamarin devs (especially experienced ones) see this.

Thanks!

«1

Posts

  • JohnHairJohnHair GBMember ✭✭✭✭✭

    @VincentH I definitely prefer coding UI in C# and I have gone down the path of creating builders for that purpose, our code looks very similar to yours indeed. I don't agree that coding UI in C# is going backwards, sorry Clint!
    XAML has to be inflated and that is a startup cost. Ok XCamlC mostly resolves that, but that has had many many issues with compatibility and stability. We are working on mobile devices and some devices just aren't that powerful.

    However, there are so many developers that are using XAML here and now with Xamarin and they absolutely cannot be abandoned. So I don't believe this situation can change.

  • VincentHVincentH USBeta ✭✭

    @ClintStLaurent Hmm, 15 years ago WinForms would be procedural code (did that too, been coding MS tech for 25+ years, currently working on enterprise mobile). But declarative C# is just like XAML; only a syntax detail change, not a structural change. But benefit is you get the best editor there is.

    Binding is same. Separation is same. Declarative is same. Only difference is XML versus C# declarative.
    Do you prefer to use tools to maintain XAML? That would be a reason to stick to XML.

    Btw parity with WPF / XAML standardization is more the domain of the twitter discussion, I created this forum discussion so as not to derail the twitter one.

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    @JohnHair said:
    I don't agree that coding UI in C# is going backwards, sorry Clint!

    That's cool. Different experiences, different teams, different needs and styles and reasons, yeild different techniques that work and preferences.

    Binding is same. Separation is same. Declarative is same. Only difference is XML versus C# declarative.

    Awesome. Then we should keep both. If they are the same only different then don't throw one away. Just like they wanted to add CSS for styling to appeal to web people (silly) - but they are keeping XAML styling so they don't piss off the existing massive XAML user base.

    @VincentH said:
    But declarative C# is just like XAML; only a syntax detail change, not a structural change. But benefit is you get the best editor there is.

    Ok. I'm all ears and open to learning new things. How is editing C# in Visual Studio so much better than XAML in Visual Studio? Both have syntax coloring, formatting, Intellisense. What are you gaining by going C# that offsets the losses?

    Do you prefer to use tools to maintain XAML? That would be a reason to stick to XML.

    'Tools'? What tools do you need to maintain XAML? I type it in and I'm done. Maybe F5 it a time or two to confirm it on a real device, make a tweak... then move on. No tools involved.

    Btw parity with WPF / XAML standardization is more the domain of the twitter discussion, I created this forum discussion so as not to derail the twitter one.

    Fair enough. I wasn't trying to go there. Just commenting on what I think needs to happen. I can't keep up on where the various discussions and bug reporting mechanisms keep getting moved. First its the forum... then twitter... then the Evolution thread on forum... bugzilla... Nuget... Honestly I think they do that in the hopes it falls through the cracks and people stop asking them to fix this or that.

  • VincentHVincentH USBeta ✭✭

    @ClintStLaurent said:
    Ok. I'm all ears and open to learning new things. How is editing C# in Visual Studio so much better than XAML in Visual Studio? Both have syntax coloring, formatting, Intellisense. What are you gaining by going C# that offsets the losses?

    In the Xamarin world the XAML editor is way inferior to the C# one. The intellisense is a big difference. Refactoring is non existent (there even is MFractor, an entire 3rd party product that gives you XAML refactoring - again partially duplicating existing C# functionality). When I change a viewmodel property name, VS updates all my markup with the standard C# rename. If VS compiles, I know that all my data bindings refer to existing viewmodel properties. When I want to see what viewmodel properties are not used, I see that in the references.

    The syntax difference is small. The IDE experience difference - in Xamarin - is big.

    What are the losses? I have not seen any yet. Could you give an example?

  • JoeMankeJoeManke USMember ✭✭✭✭✭

    I used to write all my Xamarin.Forms layouts in C#. We transitioned to XAML basically in anticipation of people with WPF backgrounds joining our team. At this point I could go either way on it.

    I do want to say I like your fluent binding API.

  • VincentHVincentH USBeta ✭✭

    @RicardoJarree Yes, I hear that a lot - it seems common sense to do what many people have been doing on different platforms for a long time. I get that, but it is also sort of a circular argument.

    The thing is, when I compare both in Xamarin, I keep the same structure and separation as with XAML, but gain the advantages of the C# editor, compile time checking, refactoring ... (see also this answer above)

    I'm curious, when you mention going back to C# do you mean procedural style or declarative style like my example above?
    What style did you create your UI in C# in?

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    @VincentH said:
    In the Xamarin world the XAML editor is way inferior to the C# one. The intellisense is a big difference. Refactoring is non existent (there even is MFractor, an entire 3rd party product that gives you XAML refactoring - again partially duplicating existing C# functionality). When I change a viewmodel property name, VS updates all my markup with the standard C# rename.

    Everyone I know or have worked with has ReSharper for the same reason. If you want to change a property in a class you right-click|Rename. Done. All the XAML references are updated as well. ReSharper is practically expected and has been supplied by the last 3 companies I've worked with. There will always be extensions that make Visual Studio easier and ReSharper does a lot on a lot of levels.

    But I wouldn't consider the rare occasion of needing to rename a property here or there reason enough to change the entire paradigm of making an app from XAML to C#. Sounds more like a case for creating naming standards and guidelines within the company to avoid the problem in the first place. Well, as much as one reasonably can. There will always be exceptions but it shouldn't happen so much that one has to make development decisions around it happening regularly.

    What are the losses? I have not seen any yet. Could you give an example?

    As @RicardoJarree points out most of a teams other UI team is already working in a variant of XML for the website, native layouts like AXML etc. Keeping the UI creation in the hands of those people and the logic in the hands of the developers does wonders. Let the designers design, and the coders code. Designers shouldn't be learning C# just to do one aspect of UI design, then flipping back to XML-ish for everything else.

    Personally I find that all UI being all XAML is a clean separation. You have a <ListView> with a <ListView.ItemItemplate>... your <Style> definitions... all that UI in the same place, same language... all blend together cleanly. You can read markup and just see what is going to be displayed because its all right there together.

    While it shouldn't happen, it always seems to happen that when people make their UI in C# they also blur the lines of separation. We all have deadlines and I get that. But logic starts creeping into the UI code due to pressure and time constraints. Its not right, but it is real-world. When UI and logic are more distinctly delineated by language and even by team member responsibility that doesn't happen... meaning that downstream problems are reduced so you aren't patching those problems.

    But again... Different projects... different companies... different war stories we can all tell. Ask the next guy and he'll have 20 other reasons to keep them separate. Then the next developer will have 10 reason to abandon XAML.

  • VincentHVincentH USBeta ✭✭

    @ClintStLaurent said:
    Everyone I know or have worked with has ReSharper for the same reason.

    Needing 3rd party tooling to partly repair (its only rename, not other refactoring or usage info) consequences of XAML will soften the pain, if you have a compelling reason to go XAML, but is not exactly a pro ;-)

    Designers shouldn't be learning C# just to do one aspect of UI design, then flipping back to XML-ish for everything else

    Yes, however in my experience designers in Xamarin projects deliver design specifications (screen mockups with layout sizes, constraint specs, color lists, fonts + sizes) and image assets, not XAML (or C#) markup. You know of designers (not developers) creating Xamarin Forms XAML in projects targeting iOS and Android without needing C# knowledge? How does that work (navigation, renderers ...)?

    when people make their UI in C# they also blur the lines of separation

    I agree that is a risk and it will happen under pressure. However setting a code review policy before a pull request can be accepted guards against that (and other bad practices as well)

  • VincentHVincentH USBeta ✭✭

    @JoeManke said:

    I do want to say I like your fluent binding API.

    Thx! I might share that sometime; it is just one C# file.

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    @VincentH said:

    @ClintStLaurent said:
    Everyone I know or have worked with has ReSharper for the same reason.

    Needing 3rd party tooling to partly repair (its only rename, not other refactoring or usage info) consequences of XAML will soften the pain, if you have a compelling reason to go XAML, but is not exactly a pro ;-)

    Well... Most shops I know consider ReSharper a pro tool.
    An I consider its use not a need for XAML so much as a way to compensate for other things, like bad standards on the onset that lead to needing to rename, or lack of good architecture put in place that has to be fix later, etc.

    Yes, however in my experience designers in Xamarin projects deliver design specifications (screen mockups with layout sizes, constraint specs, color lists, fonts + sizes) and image assets, not XAML (or C#) markup.

    Like I said. Different histories, different experiences. Yeah, where I've been the designers actually make the UI. They are the folks boasting the graphic design credentials and understanding of color theory and mobile phone usage statics like where icons have to be placed for 90% of the public to use the app one-handed and all that stuff. Plus they are the ones making the websites etc. So they can share all the style spec, art and so on for consistent product look and feel from end to end.

    You know of designers (not developers) creating Xamarin Forms XAML in projects targeting iOS and Android without needing C# knowledge? How does that work (navigation, renderers ...)?

    Like most positions there are level 1 and level 2 people. The grunts can do 80% of the work without C#. The senior people have more skills and can handle the other 20% like platform renderers. As for navigation... Navigation isn't handled in UI, or even UI code behind. That's not in the realm of graphic designers. Navigation is logic. That's handled by ViewModels and other logic classes. That's in the hands of developers

  • RasmusChristensenRasmusChristensen DKUniversity ✭✭

    I've been in MS land for a long time. Did a lot of XAML with silverlight/WPF in the earlier days. Later I did a lot of HTML and lately I've been writing a lot of XAML.

    I'm not into the whole debate about XAML version x or y or a common standard. Might be good, but I use the syntax for the tech I'm using.

    So how about the tooling? I work on both Windows and OSX meaning VS17 and vs4mac. Using tools like R# and MFractor it makes it a bit better. I can see the point in why use xaml. I did it because I new it from way back and it felt very comfortable because of that. Then again If it wasn't for a tool like MFractor, it would be a pain. UI in pure C# would just use the existing tooling, and also reduce the need for a tool like XamlC. I'm wondering if tools like LiveXAML would be able to du the same with C# UI at the moment?

    Lately I've been looking/reading about Flutter too. It's new, it's google and I would expect a new tool to get this hype.
    Compared to Xamarin and Xamarin Forms, it's a single language and UI is in Dart. Is it readable, would I write dart, I guess so.
    But at the moment I would not waste all my Xamarin investment to get onboard a new hyped tech. I follow it and love to see where it ends, and I'm sure Xamarin and Microsoft is not sleeping meanwhile. Xamarin have built a huge ecosystem, have a large number of plugins and a solid community. And tooling like AppCenter and vs4mac gets in the direction of simplifying all the trivial tasks like CI and CD. And if you look at all the documentation and learning like Xamarin University it's really hard to find someting compared to that.

    In my opinion Xamarin should not have all that focus to make you do everything on a windows machine, instead they should invest in making the product solidt and improve the development cycle. If you need a mac because of Apple license, then get one and move on.

    Lastly Xamarin put a lot of energy into preview and of course its good to know whatøs coming. But most of us using XAML for a living making production application, needs solid tooling. Live Player as an example has been hyped for almost a year, but seriously it still seems pretty har to get up and running and you still not getting what you see with Flutter hot reload.

    A bit more than a word about XAML, but I really hope Xamarin move on and move fast to improve the current tooling to keep their community happy :smile:

  • JohnHardmanJohnHardman GBUniversity mod
    edited March 13

    @VincentH said:
    So, anyone (Xamarin devs and Xamarin team) wants to chime in on either XAML versus C# or redirecting Xamarin IDE efforts?
    I'm really curious how Xamarin devs (especially experienced ones) see this.

    I currently build my UI in C# that looks very similar to yours. If I were working with a UI design person, and if there were a drag & drop XAML designer available, then I imagine we would be using XAML for the UI, with C# just for the code-behind. That's because I'd want a UI designer who can design, I wouldn't expect him/her to be able to code in C#.

    TBH, if there were a drag & drop XAML designer available, I probably would have used XAML from day #1 even when doing everything myself. In the unlikely event that I ever agreed to building something in Visual Basic, I'd use the drag & drop designer to lay out controls. Why would I do different when using C# with Xamarin? (actually, that argument can go both ways, as for HTML I would probably not use a drag & drop designer. C'est la vie).

  • JohnHardmanJohnHardman GBUniversity mod

    @ClintStLaurent said:
    I can't keep up on where the various discussions and bug reporting mechanisms keep getting moved. First its the forum... then twitter... then the Evolution thread on forum... bugzilla... Nuget... Honestly I think they do that in the hopes it falls through the cracks and people stop asking them to fix this or that.

    It's not just me then. Logged 140 bugs or thereabouts in Bugzilla. Not one since things moved from Bugzilla. No doubt I will have to when I come across something really serious, but minor ones are just getting fuzzy in the depths of my memory until I work out what I have to do to log them now. I'm sure it's nothing difficult, but too many things to do to learn yet another defect logging/tracking system, especially when there was nothing wrong with the old one that a tiny configuration tweak couldn't fix.

  • VincentHVincentH USBeta ✭✭
    edited March 14

    @JohnHardman said:

    Why would I do different when using C# with Xamarin?

    As you indicate for HTML, you make a choice based on experience with what works better.
    For Xamarin you are talking about a tool that is not there (for real world work).

    I have been in a situation where a very mature tool was available, together with an expert designer and master in that tool (WPF XAML and Blend), and I still dont want to do that again. The reason is that once a designer tool gets sophisticated enough to create real world designs, the X(A)ML that it spits out becomes unmaintainable (due to visualy fiddling around and too little XAML reuse). The only way to prevent that is to be so much aware of the XAML that the tool generates that you effectively are hand-coding XAML by pushing tool buttons. Which defeats the purpose of a visual layout tool.

  • VincentHVincentH USBeta ✭✭
    edited March 14

    @RasmusChristensen said:

    But at the moment I would not waste all my Xamarin investment to get onboard a new hyped tech.

    I'm on the same page about switching to Flutter. It is not ready.

    I even looked at how to integrate Flutter UI with Xamarin iOS and Android as a replacement for Forms; see this issue I created in the Flutter repo: Embed Flutter UI in existing Xamarin.iOS and Xamarin.Android apps

    The idea is that the markup is in Flutter and with a data binding bridge you have viewmodels and services and all the ecosystem stuff on the Xamarin side.

    However, imo Flutter is not ready to deliver native at Forms quality on iOS and Android:

    • iOS very much feels like a second class citizen. Just a few widgets version 0.x; it's not really 2 platform, more like 1.5
    • Its very phone focused; they don't even test on tablets, wearables are not supported.
    • The example apps from the app store have a sort of cartoonish feel to them; text and controls dont look and feel quite right.
    • Flutter has no equivalent of reflection (the Dart verstion of that, mirrors, is disabled in Flutter to enable the linker to keep the app size small). That means that things like JSON (de)serialization become more work.
    • Interop with native platforms is through message channels only. Would become a bottle neck for e.g. data binding
    • The extremely fine-grained composition strategy of Flutter widgets leads to extreme nesting in the Dart source; not very readable.
  • VincentHVincentH USBeta ✭✭

    @JohnHair said:

    However, there are so many developers that are using XAML here and now with Xamarin and they absolutely cannot be abandoned. So I don't believe this situation can change.

    I'm afraid you are right. Not by Xamarin abandoning XAML.
    However, it could also be the developers abandoning XAML ...

    I get it that XAML is used to get (dare I say lure?) people who are familiar with that on board with Xamarin. The real learning curve is not in the language syntax though; it is in the knowledge about all available specific layouts and controls, their properties, and which combinations (dont) work/perform well in Xamarin Forms. Devs will realize this once they are on board of course.

    However, if developers experience discomfort from working in XAML, and realize they can write the same markup in C# using their XAML knowledge with only very minor syntax differences (learning time like of a couple of hours here, they just look at a few examples and then write C# as if it is XAML), they may ask themselves ....

    • Why would I want to keep using XAML? If it only gives me more grief? If I can write the same markup in C# using my existing XAML knowledge?

    Knowledge is power :-)

  • JohnHardmanJohnHardman GBUniversity mod

    @VincentH - One question regarding your declarative implementation - if you need to wire and unwire event handlers for a View on a ContentPage (e.g. in OnAppearing and OnDisappearing), do you get the View by Id in order to do the wire/unwire? I don't currently, which on the pages where event handlers are used disrupts the declarative pattern.

  • VincentHVincentH USBeta ✭✭

    @RasmusChristensen said:

    I'm wondering if tools like LiveXAML would be able to du the same with C# UI at the moment?

    I asked Mihhail Maslakov and he said:

    Not at the moment. But it's possible to implement it if enough people are interested.

    I said I was interested, of course.
    If more people are, feel free to chime in on that tweet :-)

  • VincentHVincentH USBeta ✭✭
    edited March 14

    @JohnHardman said:

    One question regarding your declarative implementation - if you need to wire and unwire event handlers for a View on a ContentPage (e.g. in OnAppearing and OnDisappearing), do you get the View by Id in order to do the wire/unwire? I don't currently, which on the pages where event handlers are used disrupts the declarative pattern.

    I have 2 options for that, neither using ID because that would have a performance penalty (Id's are for UITest automation):

    • If I only need to wire, not unwire:
        new ListView { }.Invoke(l => l.ItemTapped += MyListView_ItemTapped),
    
    • If I want to unwire or reference the control in other methods:
        new ListView { }.Assign(out MyListView),
    
  • JohnHardmanJohnHardman GBUniversity mod

    @VincentH - Yes, the performance penalty is why I haven't done it.

    @VincentH said:

    • If I want to unwire or reference the control in other methods:
        new ListView { }.Assign(out MyListView),
    

    Nice - I hadn't thought of that. Many thanks

  • seanydaseanyda GBMember ✭✭✭✭✭

    @VincentH I built my UI in C# but I wasn't aware of the extra methods e.g SetColRow. How do you access these? The below wouldn't compile

    Content = new Grid
                {
                    RowDefinitions = {
                        new RowDefinition { Height = new GridLength(1, GridUnitType.Star)},
                        new RowDefinition { Height = new GridLength(1, GridUnitType.Star)}
                    },
                    ColumnDefinitions = {
                        new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star)},
                        new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star)},
                        new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star)}
                    },
                    Children = {
                        new BoxView { BackgroundColor = Color.Red }.SetColRow(0, 0)
                    }
                };
    
  • JohnHardmanJohnHardman GBUniversity mod
    edited March 16

    @seandya - I've got a serious hardware problem right now, so cannot check this at the moment, but it'll be something along the lines of the following (you might want to add an overload if you want a two argument SetColRow):

            public static View CommonSetColRow(View view, int left, int right, int top, int bottom)
            {
                Grid.SetColumn(view, left);
                Grid.SetColumnSpan(view, right);
                Grid.SetRow(view, top);
                Grid.SetRowSpan(view, bottom);
                return view;
            }
    
            public static BoxView SetColRow(this BoxView view, int left, int right, int top, int bottom)
            {
                CommonSetColRow(view, left, right, top, bottom);
                return view;
            }
    
  • JohnHardmanJohnHardman GBUniversity mod

    @seandya - The equivalent Assign and Bind extensions would then be (again untested due to hardware problem today):

            public static BoxView Assign(this BoxView view, out BoxView outputView)
            {
                outputView = view;
                return view;
            }
    
            public static BoxView Bind(this BoxView view, BindableProperty property, BindingBase binding)
            {
                view.SetBinding(property, binding);
                return view;
            }
    
  • seanydaseanyda GBMember ✭✭✭✭✭

    @JohnHardman said:
    @seandya - I've got a serious hardware problem right now, so cannot check this at the moment, but it'll be something along the lines of the following (you might want to add an overload if you want a two argument SetColRow):

            public static View CommonSetColRow(View view, int left, int right, int top, int bottom)
            {
                Grid.SetColumn(view, left);
                Grid.SetColumnSpan(view, right);
                Grid.SetRow(view, top);
                Grid.SetRowSpan(view, bottom);
                return view;
            }
    
            public static BoxView SetColRow(this BoxView view, int left, int right, int top, int bottom)
            {
                CommonSetColRow(view, left, right, top, bottom);
                return view;
            }
    

    Quality. Cheers for that John. I wasn't sure whether these methods were already in forms or not. That's cleared things up for me.

  • JohnHardmanJohnHardman GBUniversity mod

    @seandya - Got machine working again. Just given above code a quick test. Change CommonSetColRow as follows:

            public static View CommonSetColRow(View view, int left, int right, int top, int bottom)
            {
                Grid.SetColumn(view, left);
                Grid.SetColumnSpan(view, right-left);
                Grid.SetRow(view, top);
                Grid.SetRowSpan(view, bottom-top);
                return view;
            }
    

    I knew I was pushing my luck posting untested code ;-)

  • VincentHVincentH USBeta ✭✭

    @seanyda said to @JohnHardman :

    I wasn't sure whether these methods were already in forms or not.

    These extension methods are not in Forms, they are a set of (fairly simple) helper methods I created over the past years.

    I am considering sharing these.
    If anyone is interested, pls let me know. I think I can get it online by Monday.

  • JohnHardmanJohnHardman GBUniversity mod

    @VincentH - I'd be interested to see if you found a way to use generics rather than reproducing near identical code for each type of View. When I tried, I got a message saying that generics couldn't be used for extension methods, but I didn't spend time investigating to see if there was a way to circumvent that.

    Also, I've not yet had a need to do more than what you call Assign, Bind and SetColRow. Have you found any other methods useful (I know you show Invoke above, but are there others)?

  • seanydaseanyda GBMember ✭✭✭✭✭

    @VincentH said:
    @seanyda said to @JohnHardman :

    I wasn't sure whether these methods were already in forms or not.

    These extension methods are not in Forms, they are a set of (fairly simple) helper methods I created over the past years.

    I am considering sharing these.
    If anyone is interested, pls let me know. I think I can get it online by Monday.

    I'd be interested to have a look!

  • JoeMankeJoeManke USMember ✭✭✭✭✭

    @JohnHardman I'd be really curious to see that error message because my Visual Studio is perfectly fine with generic extension methods. Furthermore, I think most of these can just take and return BindableObject not needing anything more than that base class.

  • JohnHardmanJohnHardman GBUniversity mod

    @JoeManke - The error message is CS1106 "Extension method must be defined in a non-generic static class".

    I have the extension methods returning the specific types rather than View or BindableObject as it allows me to use them in situations other than the initial UI construction without having to cast anywhere. I'd rather use generics than basically repeating the same code for different types, but I figure repeating the code in one file is worth it to give me the flexibility of usage elsewhere.

  • JoeMankeJoeManke USMember ✭✭✭✭✭
    edited March 19

    @JohnHardman Make the methods generic instead of the class. It's a little more boilerplate but it works.

    public static class FluentExtensions
    {
        public static T Bind<T>(this T view, BindableProperty property, BindingBase binding) where T : BindableObject
        {
            view.SetBinding(property, binding);
            return view;
        }
    }
    
  • JohnHardmanJohnHardman GBUniversity mod

    @JoeManke - Genius :-) That's exactly what I was after, but as you said, I made the mistake of adding < T > on the class. Many thanks.

  • fabiorfabior USMember ✭✭

    Had Xamarin been perfect, I'd have nothing against any idea.
    But I cannot agree debates on such fundamental things like XAML since Xamarin still struggles with making Xamarin Forms stable (see ListView control as just an example).
    Xamarin Forms is long overdue to become an industrial ready product. Apart from bugs, there are fundamental concepts still missing in the framework. Just one example: ability to recreate the backstack when Activity (on Android) is recreated.

    Miguel tweeted:
    "I should have never added Xaml and instead invented our own ...", expressing regrets about having to deal with XAML (standardization) problems.

    I don't think Xamarin ever liked Xamarin Forms. Xamarin Forms is the unwanted baby, once just an experiment (like many others Xamarin likes to release but never truly complete) which took the team by surprise.
    While Xamarin part of Microsoft might seem like an obvious thing, the truth is Xamarin has nothing to do with Microsoft tooling and frameworks. I thought that once Xamarin becomes part of Microsoft, the knowledge and insight they could get from their Microsoft colleagues will help them design and create a true Xamarin Forms framework. This hasn't happened and will never happen unfortunately. Xamarin Forms remains a half baked framework, still buggy, and now Xamarin hopes open source community will do what they didn't for years. Sad.

  • seanydaseanyda GBMember ✭✭✭✭✭

    What would be the method to allow me to set the Col/Row as I'm creating the View?

    @JohnHardman @VincentH

  • JohnHardmanJohnHardman GBUniversity mod
    edited March 21

    @Seandya -

        public static T SetColRow<T>(this T view, int left, int right, int top, int bottom) where T : View
        {
            Grid.SetColumn(view, left);
            Grid.SetColumnSpan(view, right - left);
            Grid.SetRow(view, top);
            Grid.SetRowSpan(view, bottom - top);
            return view;
        }
    

    Which you would then use by

    new WhateverTypeOfView
    {
        // stuff here
    }
    .SetColRow(left, right, top, bottom);
    

    The equivalent Assign using generics would be:

        public static T Assign<T>(this T view, out T outputView) where T : View
        {
            outputView = view;
            return view;
        }
    
  • seanydaseanyda GBMember ✭✭✭✭✭

    @JohnHardman said:
    @Seandya -

        public static T SetColRow<T>(this T view, int left, int right, int top, int bottom) where T : View
        {
            Grid.SetColumn(view, left);
            Grid.SetColumnSpan(view, right - left);
            Grid.SetRow(view, top);
            Grid.SetRowSpan(view, bottom - top);
            return view;
        }
    

    Which you would then use by

    new WhateverTypeOfView
    {
    // stuff here
    }
    .SetColRow(left, right, top, bottom);

    The equivalent Assign using generics would be:

        public static T Assign<T>(this T view, out T outputView) where T : View
        {
            outputView = view;
            return view;
        }
    

    Nice one, Thanks again John!

  • seanydaseanyda GBMember ✭✭✭✭✭

    @VincentH said:
    @JohnHardman @seanyda @JoeManke
    I said:

    I am considering sharing these.
    If anyone is interested, pls let me know

    I shared my helpers on github : CSharpForMarkup.

    Feedback and contributions welcome, NJoy!

    This is awesome! Cheers @VincentH

«1
Sign In or Register to comment.