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

  • Question

  • User1520 posted

    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: ```csharp 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!

    Tuesday, March 13, 2018 1:56 PM

All replies

  • User180523 posted

    should Xamarin redirect XAML efforts elsewhere? My two centers worth: No. Building UI in C# is going backward 15 years to WinForms style development.

    XAML has been great for over 15 years of WPF development. Good binding. Good separation between design and logic. Its a great way for enterprises to make software. Xamarin just needs to get their XAML efforts on par with what already exists in WPF

    Tuesday, March 13, 2018 2:14 PM
  • User74 posted

    @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.

    Tuesday, March 13, 2018 2:32 PM
  • User1520 posted

    @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.

    Tuesday, March 13, 2018 2:40 PM
  • User180523 posted

    @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.

    Tuesday, March 13, 2018 2:52 PM
  • User271590 posted

    I tried using C# to build the UI when my Intellisense wasn't working, and at the time I thought it was the best way to make UI (mostly because I hadn't used XAML properly). However, the last year I have been using XAML and wouldn't look back. You build websites with HTML, android apps layouts with XML and WPF with XAML. So for most people a markup language is what they are used to for layout, this was the case for me! I would personally be upset if I had to go back to C# for my layouts now.

    Tuesday, March 13, 2018 3:02 PM
  • User1520 posted

    @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?

    Tuesday, March 13, 2018 3:08 PM
  • User53115 posted

    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.

    Tuesday, March 13, 2018 3:15 PM
  • User1520 posted

    @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?

    Tuesday, March 13, 2018 3:24 PM
  • User180523 posted

    @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.

    Tuesday, March 13, 2018 3:25 PM
  • User1520 posted

    @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)

    Tuesday, March 13, 2018 6:30 PM
  • User1520 posted

    @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.

    Tuesday, March 13, 2018 6:33 PM
  • User180523 posted

    @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

    Tuesday, March 13, 2018 6:47 PM
  • User109755 posted

    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:

    Tuesday, March 13, 2018 7:26 PM
  • User89714 posted

    @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).

    Tuesday, March 13, 2018 7:45 PM
  • User89714 posted

    @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.

    Tuesday, March 13, 2018 11:24 PM
  • User1520 posted

    @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.

    Wednesday, March 14, 2018 8:52 AM
  • User1520 posted

    @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.

    Wednesday, March 14, 2018 9:09 AM
  • User1520 posted

    @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 :-)

    Wednesday, March 14, 2018 9:34 AM
  • User89714 posted

    @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.

    Wednesday, March 14, 2018 9:37 AM
  • User1520 posted

    @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 :-)

    Wednesday, March 14, 2018 9:50 AM
  • User1520 posted

    @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: csharp new ListView { }.Invoke(l => l.ItemTapped += MyListView_ItemTapped),

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

    Wednesday, March 14, 2018 10:25 AM
  • User89714 posted

    @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: csharp new ListView { }.Assign(out MyListView),

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

    Wednesday, March 14, 2018 10:30 AM
  • User171749 posted

    @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

    CSHARP 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) } };

    Friday, March 16, 2018 11:37 AM
  • User89714 posted

    @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;
        }
    

    ```

    Friday, March 16, 2018 12:18 PM
  • User89714 posted

    @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;
        }
    

    ```

    Friday, March 16, 2018 12:22 PM
  • User171749 posted

    @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.

    Friday, March 16, 2018 1:16 PM
  • User89714 posted

    @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 ;-)

    Friday, March 16, 2018 7:31 PM
  • User1520 posted

    @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.

    Saturday, March 17, 2018 8:33 AM
  • User89714 posted

    @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)?

    Saturday, March 17, 2018 11:58 AM
  • User171749 posted

    @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!

    Monday, March 19, 2018 8:16 AM
  • User53115 posted

    @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.

    Monday, March 19, 2018 2:29 PM
  • User89714 posted

    @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.

    Monday, March 19, 2018 3:17 PM
  • User53115 posted

    @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;
        }
    }
    
    Monday, March 19, 2018 3:21 PM
  • User89714 posted

    @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.

    Monday, March 19, 2018 3:47 PM
  • User275358 posted

    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.

    Monday, March 19, 2018 4:01 PM
  • User171749 posted

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

    @JohnHardman @VincentH

    Wednesday, March 21, 2018 3:02 PM
  • User89714 posted

    @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;
        }
    
    Wednesday, March 21, 2018 4:42 PM
  • User171749 posted

    @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!

    Wednesday, March 21, 2018 5:00 PM
  • User1520 posted

    @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!

    Thursday, March 22, 2018 3:17 PM
  • User171749 posted

    @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

    Thursday, March 22, 2018 4:14 PM
  • User19820 posted

    @VincentH

    I personally like XAML over code-behind mainly because: - it's coincise, it's impersonal (although formatting preferences can differ) - easier to maintain

    Code always has so many ways of looking more personal, from naming variables to structuring. XAML can have some of that too, but to much less extent. When you open a XAML, you know exactly to expect, for the most part. I also like it has an intrinsec separation, it doesn't allow you to mix different concerns, it's focused on the view.

    @VincentH said: Advancements in C# (declarative syntax) have eliminated any advantages of a separate markup language for years.

    In my opinion, no matter how cool or advanced the C# syntax gets, it doesn't matter, it's still code (or better said, it's code-behind).

    Thursday, March 22, 2018 5:07 PM
  • User48551 posted

    I did c# UI on my first Xamarin project, and ended up rewriting it in XAML, but I'd gladly give it another try now after 2 years of Xamarin development. I'd also like to note that I have no previous experience with XAML or anything desktop related coming from web development.

    I like your helpers and the approach, also the focus of Xamarin team that you point out. Do you think we can further expand this and maybe turn it into an OSS project?

    I'll also make some pages to get a better overview of the helpers and compare full pages XAML vs C# and will be back with results :)

    Friday, April 13, 2018 11:09 AM
  • User6349 posted

    Really good discussion here. Thank you for facilitating this, @VincentH. My take on this is that the primary point of enabling a format is cost savings. Whereas you had issues with the Blend->WPF workflow, I have had magic with it many times. The workflow between designer and developer is critical. A serialized format enables this at a much granular (and CHEAPER) degree than compiled code (or coded/scripted language).

    Additionally, a (compiled/scripted) language-agnostic serialized data format leads to a lower total cost of ownership for an application than one that is strictly code-based. If I have to hire a resource that simply has to maintain a data file for a project vs. having to get someone to manage code to make pixels move or otherwise configure the behavior of an application, that usually involves a lower rate per hour and therefore improved bottom line on the budget. This is even magnified when that data file can be easily edited by way of a visual designer. Now my maintenance requirement has moved from someone who understands a (language-agnostic) data format to someone who knows how to press buttons and make pretty pictures with an editor (that is based on a serialized and standardized data format). This is ultimately cheaper for me and the clients for which I have to acquire the resources to do this. If it's all compiled/scripted code, well, that is MUCH more expensive and therefore a higher barrier to pursue and keep to budget.

    The primary problem this space faces is tooling and innovation around such. WPF was very close to touching an ideal but certainly could have been improved (as you can attest @VincentH). But, not bad for a first shot at it, IMO. :) The problem of course is that a 2nd shot was never attempted and we are still suffering for answers to this day.

    BTW, I did read flutter's philosophy here and I am not in agreement whatsoever. I also am/was not impressed that Flutter does not even work on the web, nor plans to. Some innovation. :P

    Friday, April 20, 2018 9:20 PM
  • User230357 posted

    Really nice to avoid XAML with its primitve to non-existent type system. And to avoid bindings with all the boilerplate and value converter hacks.

    In F# my UI code looks like:

    ``` let qL = Label( FontSize=22., Style = LabelStyle.StandardLayout, TextColor = Color.Red) do vm.QLabel |> bind (fun s -> qL.Text <- s)

    Grid( BackgroundColor = Color.White, ColumnSpacing = 1., ColumnWidths = [GridLength 200.; GridLength.Star; GridLength 50.], Row0 = [scoreL; qL; prevB] ) ```

    Wednesday, May 2, 2018 7:50 PM
  • User6349 posted

    @CharlesRoddie I am with you on the converter hacks, but Xaml (WPF's at least) has a great type system. Or I should say better than average, these days. Have you ever tried using using XmlSerializer or even DataContractSerializer? Additionally, the boilerplate dilemma is always a problem with MSFT products as the code they place in projects/project items are notoriously filled with poor practice and unnecessary code.

    Also, I am a fan of F# but first show me a designer (both visual design tool and human) that can work with the code you have presented and THEN I will be impressed. ;) The goal here is to leverage the talent and expert system provided by a UI/UX resource, via a medium that is easily accessible by them with the least amount of friction possible incurred. What you are proposing involves this resource to learn an proprietary language in order to provide any sort of meaningful value towards a production. Not the most viable (or profitable, I should say) of options/strategies. Knock yourself out if it works for you, though. :)

    Thursday, May 3, 2018 11:01 AM
  • User230357 posted

    That is fair. But in order for Xaml to work well, the type system can't just be better than average. It has to be as good as the .Net type system. This is because properties of View objects may be of any type.

    An intermediate approach of defining a limited set of UI objects and supplementing with code (for bindings or more advanced types) would work OK and Xaml can do that. (Can use type providers in this way.)

    As is it works OK if you don't mind verbosity, magic strings, and a pseudo-reactive binding approach that ties not only the view but also the viewmodel to a specific UI framework.

    Thursday, May 3, 2018 9:18 PM
  • User209348 posted

    @fabior said:

    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).

    this!

    Thursday, May 3, 2018 11:12 PM
  • User209348 posted

    @fabior said: 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.

    haha.. this is so true... It's as if they had a board meeting and said, 'hey we get the entire world to QA our software at no cost, why don't we take it to the next level and get them to also develop our software too' ...

    Smart move Xamarin, smart move! :neutral:

    Thursday, May 3, 2018 11:15 PM
  • User1520 posted

    @AndrewMobile said: Code always has so many ways of looking more personal, from naming variables to structuring. XAML can have some of that too, but to much less extent. When you open a XAML, you know exactly to expect, for the most part.

    I recognize from several reactions that some limitations of XAML can be used to an advantage (as a famous soccer genius once said, "every disadvantage has it's advantage"), if you need to ensure that developers stick to standard syntax, conventions and good separation.

    While limiting others can keep them from mischief, it also reduces their productivity, and makes them less happy about their jobs.

    Consider that you may achieve more with existing code quality control measures that do not limit productivity. E.g. if you put the helpers in a NuGet, effectively defining the markup DSL for your team(s), you can easily ensure standardization of your declarative C# files content in a build step or an analyzer, failing or warning when people check in code that violates your standards.

    Friday, May 4, 2018 5:59 AM
  • User1520 posted

    @MikeEEE said: If I have to hire a resource that simply has to maintain a data file for a project vs. having to get someone to manage code to make pixels move or otherwise configure the behavior of an application, that usually involves a lower rate per hour and therefore improved bottom line on the budget.

    I see your point, however this is more about semantics when hiring people. If you would hire a "Xamarin Forms markup maintainer", and that person knows only XAML, they do not need to become a full fledged C# developer to become productive in declarative C# markup. Their real skills and learning curve are knowing the Xamarin Forms layouts and controls and how to use them. Learning a slightly different syntax should only require a few hours of practice and inspecting existing markup, because the C# reads almost identical to the XAML and the intellisense in C# is much better.

    Consider below images from https://github.com/VincentH-Net/CSharpForMarkup. Does that look like it requires an higher hourly rate?

    Also consider that the main point is that declarative C# is more productive than XAML. Given the same hourly rate, that would mean that declarative C# is less expensive than using XAML.

    Even more so when maintaining markup, because of the better refactoring support in Visual Studio. E.g. when a viewmodel property is renamed in code, all the bindings are renamed automatically in all markup files. When you compile, all bindings are checked, no more binding errors that are only discovered when running the app. Code Lens tells you where (and whether) viewmodel properties and commands are used, allowing you to quickly assess the impact of changes and to remove unused code.

    Here are some side by side comparisons: Entry markup: Entry in XAML XAML Entry in C# C#

    Registration code page in XAML:

    Registration code page in C#:

    For more examples, see https://github.com/VincentH-Net/CSharpForMarkup

    Friday, May 4, 2018 6:36 AM
  • User6349 posted

    @VincentH I appreciate the engagement in dialogue here. To start, all of the features you are describing are indeed part of the Visual Studio development process which is indeed quite expensive. All the screenshots you demonstrate here are in C#, so this (again like with F#) would require a resource to attain the knowledge of how to operate in such a system and corresponding language. Having spent what is approaching nearly 20 years in the subject myself I can assure you it will take them more than a few hours to onboard an become proficient at this. :)

    Consider that all of the features towards stabilizing the development experience are tooling-related, all of which can be also applied to a visual designer/tool as well.

    Along such lines, consider that visually inclined individuals (in my experience) want nothing to do with the code editor and prefer visual designers/tooling, and that is what I am personally angling for in my discussion here. A visual designer or additional tooling like Blend would be able to work with the formatted language like Xaml (or XML or JSON or YAML) and provide a more congruent, productive experience like what you are suggesting.

    Also consider that with a formatted data language you have the opportunity to provide additional semantics with expressions (such as bindings, or specifically markup extensions) that further mitigate costly (repetitive) tasks. Of course, this doesn't always pan out as we have already mentioned earlier with the converter hacks required for XAML-binding. However, I would suggest that this is a limitation of the language however and not the workflow which I am espousing.

    The point being that any data language that continues to evolve will improve upon it, much like a coded language. Unfortunately, we simply have not seen Xaml evolve like C# has over the years.

    I would also like to mention that attempts have been made in the past to "codify" UI and haven't been too successful. Nothing beats a visual experience. HOWEVER that is not to say that you won't be successful in your approach. If anything, I am glad to see you promote the greatest feature of Xaml which was for all intents an purposes an CLR object graph serializer. In fact, we call it Xaml but at the end of the day it was ultimately compiled into C#/IL via the .baml graph embedded in the assembly.

    Finally, I am not sure if you have tried WebFlow yet, but I find it really amazing. I would love to see something like this for .NET. I look at the experience it offers versus the experience you are describing above and it is simply not even a contest. However, that is just MY opinion and I wish you the best of luck in your efforts. Much like I was saying earlier ... if it works for you then all the power, Brogrammer!

    Friday, May 4, 2018 9:09 AM
  • User246900 posted

    I've always created my UI using C# but I'm now mostly using XAML (Expecially now that I user LiveXAML).

    I have to say that I've completely rewritten an app to design my UI in XAML while it was written in C# and this is what I can tell of my experience:

    Why you should prefer XAML:

    It's cleaner You can separate you UI from your code in a better way With some tools you can see immediately what you are writing and this case save you hours!

    Why you should prefer C#:

    It's faster to run You can reuse a lot of your code You have more control over your UI (if you want a pixel-perfect UI)

    I have to say that in this moment I think that XAML is better that C# for UI but maybe it can change in future...especially is LiveXAML can implement its live preview with C# (this is the main reason why I'm now using XAML)

    Friday, May 4, 2018 9:43 AM
  • User1520 posted

    @MikeEEE said: Along such lines, consider that visually inclined individuals (in my experience) want nothing to do with the code editor and > prefer visual designers/tooling, and that is what I am personally angling for in my discussion here.

    Thx Mike, that clarifies what your goal is here, which fits this discussion very well. Blend once was pretty good for WPF (worked for you, but didn't for me).

    Regrettably, there currently is no designer tool for Xamarin that comes anywhere near to what Blend was. People creating Xamarin production apps with XAML today use Visual Studio and run the app to see the UI; the VS designers simply can't display the UI due to their many limitations. My low time estimate for switching to declarative C# is for people already working with VS this way, as illustrated in the screenshots, given existing tooling.

    To get at Blend(+) level tools, you would need much more XAML tooling effort from the Xamarin team(s). The reason I started this discussion, given that the teams are too small as it is, was to redirect their scarce time to improvement of the core frameworks and tools.

    Who knows, maybe Microsoft will grow the Xamarin teams a lot and we will both get what we want :-)

    Friday, May 4, 2018 9:59 AM
  • User1520 posted

    @MarcoTroncone said: I have to say that in this moment I think that XAML is better that C# for UI but maybe it can change in future...especially is LiveXAML can implement its live preview with C# (this is the main reason why I'm now using XAML)

    This is spot on Marco - the main reason for you switching to XAML is the tools. It so happens that as a result of this discussion, I am working with the LiveXAML creator Mihhail Maslakov to support declarative C#; he already has the declarative UI examples at https://github.com/VincentH-Net/CSharpForMarkup working in LiveXAML

    Once that is working... :-)

    Friday, May 4, 2018 10:13 AM
  • User19820 posted

    @VincentH said:

    @AndrewMobile said: Code always has so many ways of looking more personal, from naming variables to structuring. XAML can have some of that too, but to much less extent. When you open a XAML, you know exactly to expect, for the most part.

    I recognize from several reactions that some limitations of XAML can be used to an advantage (as a famous soccer genius once said, "every disadvantage has it's advantage"), if you need to ensure that developers stick to standard syntax, conventions and good separation.

    While limiting others can keep them from mischief, it also reduces their productivity, and makes them less happy about their jobs.

    If you think that using XAML means "makes them less happy about their jobs" then I guess all Windows XAML developers using WPF\Silverlight\UWP must feel miserable :)

    @VincentH said: Consider that you may achieve more with existing code quality control measures that do not limit productivity. E.g. if you put the helpers in a NuGet, effectively defining the markup DSL for your team(s), you can easily ensure standardization of your declarative C# files content in a build step or an analyzer, failing or warning when people check in code that violates your standards.

    Yes sure, you can setup different build things to ensure code standards, but if you think that's easier to than just sticking to XAML, which is simpler and more precise, then go for it.

    I am not sure what is the point you're trying to make to be honest. You seem like you have some strong opinions against XAML for some reason, even though you perfectly understand it. You are trying to promote the idea that "Xamarin should redirect XAML efforts elsewhere". Not really sure what's the point of this rant. Xamarin Forms going away from XAML, removing features, is the last thing Xamarin Forms would need, like it doesn't have enough problems already.

    If you have any constructive ideas how to improve Xamarin Forms, I'd be happy to applaud and discuss.

    Friday, May 4, 2018 12:34 PM
  • User230357 posted

    @MikeEEE said: I am with you on the converter hacks, but Xaml (WPF's at least) has a great type system. Or I should say better than average, these days.

    Just look at this issue: https://github.com/xamarin/Xamarin.Forms/issues/2753 "[Binding] use DefaultValue on failed type conversion"

    It's clear from this that bindings have no type-safety. And bindings underlie real-world xaml usage. This is not better than average. It's vastly inferior to any static type system out there.

    Thursday, May 17, 2018 12:57 PM
  • User6349 posted

    If I am not mistaken @CharlesRoddie that is the Xamarin Forms Xaml Model, not WPF's model, which I was referring to, in your quoted material of me. :smile:

    Additionally, after studying this for a bit, I believe you were/are (rightfully) concerned with type safety whereas I was/am more concerned about the serialized type model. In your case, the example you provide is an excellent one and I am in agreement.

    To clarify my point further, I was drawing a comparison to other serialization mechanisms such as the classic XmlSerializer and the DataContractSerializer. Both of these struggle mightily with recognizing basic .NET type model constructs (e.g. interface properties), and was actually one of the many reasons I felt compelled to write ExtendedXmlSerializer. (Warning: shameless plug. :lol:)

    With WPF and Silverlight, you have the ability to utilize the design-time namespace and DesignInstanceExtension to declare the types of objects you will be working with at runtime, which assists tooling in providing the appropriate feedback when creating your bindings. And, as far as I can recall, the DefaultValue and TargetNullValue properties can be used in conjunction to yield the desired result in the referenced GitHub issue -- in WPF's Xaml model.

    However, all said, I would say that you are correct in your sentiment, @CharlesRoddie. But also, keep in mind that WPF is going on a decade now in age. F# and other type systems (Haskell is the tops from what I have been reading) that have been created since then have produced certain expectations for current tooling that simply was not there when WPF/Xaml/Silverlight was created.

    That's probably a good segue into saying that I have been giving this problem space and area a little more thought, and given the constraints and resource challenges that are being faced here, I think @VincentH's approach is a good one. Keep in mind that I am not invested in Xamarin Forms like everyone here is, and my ideas/notions are rooted in the past and more in theory rather than in the here-and-now with actual investment and application (pardon the pun). I thought about your last response to me @VincentH and if I were in your shoes, your approach here would make sense to me, as well, FWIW. :+1:

    Thursday, May 17, 2018 1:43 PM
  • User230357 posted

    This all makes sense. (Except Haskell is from 1990.) More relevant than other languages is .Net generics which came at the same time as WPF, in 2006. It's a shame that WPF's binding framework didn't make use of generics, and that Xamarin.Forms copied WPF.

    Thursday, May 17, 2018 4:21 PM
  • User6349 posted

    Wow I had no idea that Haskell is that mature. FWIW, I have been following Mark Seemann's Blog for some time now and have been reading the good things about Haskell (and of course F#) there. I am certainly interested in any additional F#/functional resources/urls/blogs if anyone has others that they frequently visit.

    (Also, speaking of feeling compelled, I should clarify to avoid misrepresentation that I helped write ExtendedXmlSerializer -- specifically v2, and am one of two primary authors in the repository. I would've edited my earlier post but there is a time limit on this forum in doing so. I was too focused on my shameless plug and we can see where that got me. :wink: )

    Saturday, May 19, 2018 8:27 AM
  • User378795 posted

    @VincentH Resurrecting an old thread, but this discussion is becoming increasingly relevant with the release of Flutter 1.0 and widespread adoption.

    I think your original post points out one major advantage of Flutter over Xamarin.Forms, but in my view there are four major innovations in Flutter that need to be addressed if Xamarin.Forms is to remain competitive:

    1. Declarative code-based layout, as opposed to XML-based layout. For all the reasons you stated in your original post. Now, C# is not (yet) the best language for declarative markup style APIs, but things have improved a little with C# 6/7/8, so we might be getting there. Of course there's always F#, which is AMAZING at declarative markup style APIs.
    2. Declarative C# UI definitions aren't enough. Flutter's react-style immutable UI framework has major benefits over the mutable UI with data-binding system of XAML based UI frameworks. This can't be added to Xamarin.Forms without creating a new independent layer or shadow DOM on top of Xamarin.Forms, which for many reasons is not the right path to take (see the many articles on why people moved from react native to flutter).
    3. Flutter does not use native controls - it draws everything to a Skia surface. Thus, your application looks, down to the pixel, exactly the same on all platforms you run it on. This is a MAJOR improvement over Xamarin.Forms use of native controls. A huge portion of the Xamarin.Forms bugs and my time as a developer spent testing and tweaking styling and layout on each individual platform. In Flutter the UI is almost pixel perfectly consistent on every platform. This also allows Flutter to be far more efficient and smooth, particularly with respect to scrolling and animations.
    4. STATEFUL Hot reload. Cannot stress enough how huge an advantage this is over Xamarin.Forms. It takes over a minute between making a UI change and seeing the results. With Flutter, changes are refreshed instantly.

    This post isn't a Flutter endorsement, but I think it's important to understand fully where the weaknesses and challenges are. The declarative C# framework takes care of point 1, but point 2 can't easily or efficiently be bolted onto the existing Xamarin.Forms framework. Point 3 could be implemented with custom platform renderers, but you lose many of the advantages without immutable UI as in point 2. Point 4 - I just don't know how that could be implemented in Xamarin.Forms. Flutter's runtime works together with the framework to preserve state and enable fast hot reloads of code at runtime. What is the equivalent on Mono/Xamarin runtime? Interpreted DLLs?

    Tuesday, December 18, 2018 5:14 PM
  • User76049 posted

    @JeroMiya said: @VincentH Resurrecting an old thread, but this discussion is becoming increasingly relevant with the release of Flutter 1.0 and widespread adoption.

    I think your original post points out one major advantage of Flutter over Xamarin.Forms, but in my view there are four major innovations in Flutter that need to be addressed if Xamarin.Forms is to remain competitive:

    1. Declarative code-based layout, as opposed to XML-based layout. For all the reasons you stated in your original post. Now, C# is not (yet) the best language for declarative markup style APIs, but things have improved a little with C# 6/7/8, so we might be getting there. Of course there's always F#, which is AMAZING at declarative markup style APIs.
    2. Declarative C# UI definitions aren't enough. Flutter's react-style immutable UI framework has major benefits over the mutable UI with data-binding system of XAML based UI frameworks. This can't be added to Xamarin.Forms without creating a new independent layer or shadow DOM on top of Xamarin.Forms, which for many reasons is not the right path to take (see the many articles on why people moved from react native to flutter).
    3. Flutter does not use native controls - it draws everything to a Skia surface. Thus, your application looks, down to the pixel, exactly the same on all platforms you run it on. This is a MAJOR improvement over Xamarin.Forms use of native controls. A huge portion of the Xamarin.Forms bugs and my time as a developer spent testing and tweaking styling and layout on each individual platform. In Flutter the UI is almost pixel perfectly consistent on every platform. This also allows Flutter to be far more efficient and smooth, particularly with respect to scrolling and animations.
    4. STATEFUL Hot reload. Cannot stress enough how huge an advantage this is over Xamarin.Forms. It takes over a minute between making a UI change and seeing the results. With Flutter, changes are refreshed instantly.

    This post isn't a Flutter endorsement, but I think it's important to understand fully where the weaknesses and challenges are. The declarative C# framework takes care of point 1, but point 2 can't easily or efficiently be bolted onto the existing Xamarin.Forms framework. Point 3 could be implemented with custom platform renderers, but you lose many of the advantages without immutable UI as in point 2. Point 4 - I just don't know how that could be implemented in Xamarin.Forms. Flutter's runtime works together with the framework to preserve state and enable fast hot reloads of code at runtime. What is the equivalent on Mono/Xamarin runtime? Interpreted DLLs?

    1. That's personal preference, hate code based UI's but for really complex layouts, I'm sorry but XAML makes managing large projects easier in my experience, last app has over 100 pages.
    2. There's effortsbenefit if it supported native control rendering and Skia rendering for controls, Telerik's control suite is already a mix of both as it has a Skia dependency. Also clients/designers DO want native behavior, in my experience they want a mixture of both.
    3. You buy LiveXAML and you have that in Forms

    What you don't have with Flutter is as strong an eco-system as .net, nowhere near it, I couldn't recommend a platform that has over 4000 open issues currently.

    I haven't seen Flutter jobs advertised tbh, it's still new and people will dip their toe in the water, I do see people crying out for Xamarin devs, it's more mature and has strong eco system making it a less risky choice, so to say it's been widespread adoption for Flutter, I'd need to be convinced.

    It's looks very good but Dart is not as nice as C# hence Adam's efforts with Fluttersharp to try and bring the .net eco system into Flutter.

    It's fascinating and I keep a close eye on where it's going, for creative Flutter may gain quick traction, for Enterprise dev, I'm not so sure at all. A lot of us like XAML based UI's though, it get's a little tiresome when people propose only code based approaches.

    Tuesday, December 18, 2018 8:36 PM
  • User76049 posted

    The key people within MS are listening...

    https://twitter.com/migueldeicaza/status/1071394748831805440

    Tuesday, December 18, 2018 8:41 PM
  • User378795 posted

    @NMackay So first of all, I also much prefer C# and .NET to Flutter and Dart. I'm just pointing out places where Flutter has some advantages over Xamarin.Forms in the hopes Xamarin.Forms (or even a new framework) heads in a good direction and remains competitive. .NET does not currently have a good Reactive style UI framework with consistent vector based control rendering. It's something some developers want and prefer, but which doesn't have a first-class Microsoft-funded solution.

    As for the XAML vs Code debate - there's no reason both can't be supported. In fact Xamarin.Forms technically supports both now - however the API isn't very conducive to declarative code-based layout, which is why @VincentH made a library to improve that experience. If you're going to support code-based layout, the API needs to be adjusted to help make that less painful, especially in C# which is a bit verbose for those kinds of things (which is a valid point in favor of XAML, at least if you're using C#). I mention it along with the reactive style immutable UI because that style of UI framework typically starts with a top level function for building the UI, and has a declarative or fluent API. It's there that you would inject a XAML based layout. Something like this:

    public Widget Build() => new XAMLWidget("./MyPage.xaml");

    And even this could be auto-generated for you when you have a XAML/CodeBehind pair.

    As for adoption rates and developer mindset - we may be in different developer circles. I've been hearing about it a lot, especially since the 1.0 release. It's very popular in the dev conference scene, and it's getting a lot of buzz. There's nothing inherently enterprise-unfriendly about it other than a lack of high quality charting and data grid controls, and those will come sooner or later.

    More broadly, the react style immutable UI framework design has been winning over developers from template/MVVM based frameworks. For example: adoption rates of React (which works like Flutter) are pulling ahead of Angular (which works more like XAML/MVVM) by a wide margin.

    Tuesday, December 18, 2018 9:48 PM
  • User76049 posted

    "As for the XAML vs Code debate - there's no reason both can't be supported"

    Agreed.

    Tuesday, December 18, 2018 9:52 PM
  • User180523 posted

    Personal two cents worth...

    For example: adoption rates of Statistics in many cases are meaningless or manipulated to the desired result by the entity collecting them. For example: CSS was added to Xamarin.Forms and suddenly the "adoption rates" went through the roof. That doesn't mean its actually used by developers for real programs. That just means that everyone that was already registered as a web developer was now classified also as a Xamarin developer since technically they could make UI using CSS (what a truly horrible thing). But it makes the numbers look great.

    No different than when Xamarin was bought and made free instead of paid or part of only the Enterprise version of Visual Studio. Suddenly there were 5 million more users. Well... Not really because not every Visual Studio user was a Xamarin user. But it sure boosts the statistics if every VS install is classified as a Xamarin user.

    I agree that's its fine to support both. No argument there. Let C# be used to make UI just like XAML. Fine.

    But what do you say they fix the underlying mechanisms and controls first? What's the point of adding 1:n different ways to make UI if the UI itself is broken? It doesn't matter if its made with XAML or C# or F# or ButterflyTears.

    There are still countless bugs (formerly bugzillas) that haven't been fixed since original reports 3 years ago.

    All I'm saying is that since there isn't unlimited man power... Prioritize. Fix the borked stuff. THEN add new ways to access that stuff. Doesn't seem like rocket science.

    Tuesday, December 18, 2018 10:00 PM
  • User378795 posted

    Yep, seems like there's some consensus on these points. Bug fixing should have a priority. Supporting both XAML and declarative C# - seems like a good idea.

    ButterflyTears is an awesome name for a programming language or tool, by the way.

    Wednesday, December 26, 2018 4:17 PM
  • User172704 posted

    I'm undecided on this issue.

    I currently mostly work alone so am probably not a typical Xamarin developer. I haven't found any disadvantages with using XAML lately (now initial bugs have been fixed) but I haven't found any advantages either.

    There is one feature that is missing from Xamarin XAML (and also to my knowledge missing in WPF XAML) and that is support for conditional compilation.

    I currently have a couple of screens that have a 'Debug' control somewhere on them. This has to be added in code. And sometimes it is not easy, because I might want to change exactly where, how and what is added to the screen's visual tree in Debug builds.

    If I wanted, say, a button in only Debug builds, I guess I could add it with a name in XAML and simply set its visibility in C# but this doesn't seem like much of an improvement.

    • Patrick
    Wednesday, January 9, 2019 12:04 PM
  • User97623 posted

    This is awesome! I have been using coded UI with Xamarin.Forms for a while now, mainly for performance, but also for dynamic reasons, and this really assists with that. I was a WPF developer (and VB6 before that), so I have seen the worst I agree a markup language is not always the best solution to every problem. I do agree it should still exist, but I also agree investment in the Xamarin team shouldn't be spent on making new designers - to me designers are so VB6 - they shouldn't exist in modern software dev. Apples Interface designer a case in point - it is horrible

    Friday, January 11, 2019 12:38 PM
  • User378795 posted

    So this project is focused on F#, and I don't know if it can be used cleanly from C#, but I thought it was very interesting and provides both a declarative layout API and an immutable UI/state reactive style API similar to Flutter/React. And, it "renders" its internal UI representation to Xamarin.Forms (with efficient diffs/etc..):

    https://fsprojects.github.io/Fabulous/

    Those F# folks are way ahead of us! :P

    Wednesday, January 16, 2019 7:47 PM
  • User268349 posted

    Main advantage of using XAML for me is I no longer need a separate ViewModel. XAML is View and code behind is ViewModel. This greatly simplifies the application architecture

    Thursday, January 17, 2019 6:42 AM
  • User180523 posted

    @VovaKamishnikov said:

    Main advantage of using XAML for me is I no longer need a separate ViewModel. XAML is View and code behind is ViewModel. This greatly simplifies the application architecture

    Then you have no understanding of MVVM. Code behind the UI is NOT the ViewModel.

    The point is you ARE supposed to separate view and viewmodel. ViewModel knows nothing of the 0:n views that are using it as the binding context. You could have 50 different views all using the same VM as its binding.

    If its your intention to one day get paid to do development I URGE you to stop coding until you can take the time to LEARN. The longer you keep doing it wrong the harder it will be to unlearn all the bad concepts and practices - and you'll still have to go through the learning process to understand the correct way to do things. There is no positive reason to keep going the way you are.

    Thursday, January 17, 2019 12:53 PM
  • User268349 posted

    @ClintStLaurent said:

    Then you have no understanding of MVVM. Code behind the UI is NOT the ViewModel.

    Why not ? My typical codebehind-ViewModel is just an ordinary ViewModel

    @ClintStLaurent said: You could have 50 different views all using the same VM as its binding

    Do you really have many views for one VM in Xamarin Forms ?

    @ClintStLaurent said: There is no positive reason to keep going the way you are.

    Definitely is. It makes everything so much easier

    Thursday, January 17, 2019 5:07 PM
  • User129559 posted

    Is the world really that much easier than creating another file for your VMs?

    It takes about 2 seconds to make a file and reference it in your page.

    But this ignores things like Unit Testing your VMs as now you are tied to the Xamarin ecosytem for that.

    At least for testability, the 2 seconds a separate file takes win out.

    And while I usually only have 1 view with my viewmodel, there are plenty of cases I have had multiple views using the same view model.

    Thursday, January 17, 2019 5:50 PM
  • User180523 posted

    Its not a ViewModel if its the code behind for the View. That's the point I'm trying to make. You have your terms confused. If its the code behind a view... and it knows anything about the view, then its View layer not data/logic which is what a ViewModel is.

    Do you really have many views for one VM in Xamarin Forms ? Absolutely. Just one example: Human Resources app or a scheduling app. You might have 10 different views pertaining to an Employee or a Shift. But they still all use the ShiftViewModel because that's where all the data pertaining to a work shift resides. But one View is a calendar layout. One view is a manager's view. One view is limited to just the employee view. and so on.

    Look. Its no skin off my nose. But just to let you know... If you're just doing hobby coding for yourself then do it however you like. But if you're hoping to work for a company developing software one day... What you have there is so far out of practices and standards that if you submitted it as part of a coding test at an interview it would nearly certainly get your resume shuffled to the bottom of the pile. I don't say that to be mean. Like I said, what you do and how you do it doesn't affect me. I'm just trying to help guide you back in the right direction if it matters for your future plans.

    Thursday, January 17, 2019 5:51 PM
  • User268349 posted

    @AdamMeaney said: Is the world really that much easier

    I've written separete VMs for many years and I say yes it's really much easier have VM in code behind

    @ClintStLaurent said:

    Do you really have many views for one VM in Xamarin Forms ? Absolutely. Just one example: Human Resources app or a scheduling app. You might have 10 different views pertaining to an Employee or a Shift. But they still all use the ShiftViewModel

    No problem. I'd create base class ShiftViewAbstract

    Friday, January 18, 2019 7:20 AM
  • User378795 posted

    If you're following the MVVM architecture, both the XAML and the code-behind are part of the "View". XAML is merely a convenient declarative language to define your UI layout, instead of C# code. Otherwise there is no difference architecturally between XAML and C# code-behind. Some would say it's better to define everything in XAML and have no code-behind, but in practice this is unnecessary and in many cases counter-productive. Some things, like triggering animations etc... are easier to implement in the code behind. It doesn't mean you aren't following MVVM, it just means the "View" part of your architecture is defined in both XAML and C#.

    That being said, it is true that splitting view code between two files, and indeed two languages, can make the code a little harder to follow. In this case, you can either develop a library of XAML extensions/behaviors/etc... to help move your C# code-behind into your XAML, or go the other way and have a library that makes defining your layout completely in C# instead of XAML easier and more readable.

    Tuesday, March 12, 2019 1:17 PM
  • User94069 posted

    Sincere thanks to @VincentH for starting this thread. It's still valid!

    I took a break from Xamarin development for a year or two, came back, and found myself asking the same question about using XAML or C#. WOW, this thread has been educational. I've found myself appreciating both declarative #C and XAML more, for what each does well and perhaps better than the other.

    When working with ASP.NET, I was constantly fighting with the markup, trying to get it just right, and then trying to get code-behind to work with it in harmony. The ongoing irony is "I am declaring that I want you to look like this, and now I'm going to make you do a lot of different things in code". I feel the same about XAML where we declare a fixed UI and then get the back-end to conform. I feel like my thought process is highly focused on working within the confines of that declared definition, (OK, perhaps that's good) when I really prefer to be thinking about a much more fluid (though not chaotic) UI.

    With XAML (also a thing with ASP.NET), we are also highly subject to the notion of having to ask for a widget/control/view by ID. While a small annoyance I think it's a degree of separation inherited from common beginner Android coding with Java that we don't need. When you're building the component in C#, you don't need to ask XAML for a reference to that object - you already have it. Yes, you still need to create it "somewhere" but with code you create an object and manipulate it in the same place. Why do it in two places/languages?

    But if one uses C# to write code in a format that echos XAML, then all we're doing is substituting syntax, albeit adding extension methods as discussed in this thread. Personally I'd prefer to build every component in its own function, composing the layout and various nested layouts and views modularly. It seems much more elegant to return a Layout from a method, and add that as a child to another layout, rather than hardcoding a new derived Layout like StackLayout or Grid. I'm talking descriptive development rather than prescriptive - which is what I thought markup was supposed to be about in the first place ;) . Then we get a lot more code re-usability from both the code that builds the Content and the code that builds the Views. We see this to an extent in modularized XAML as well, but then the XAML for a page will include another XAML file with its own hard-coded layout.

    In terms of composition, it also seems more natural to abstract out code for layouts and views into their own classes. So rather than XAML like

    <include layout="@layout/order_header" />

    That's very rigid. I'd much prefer:

    class OrderHeaderLayout : Layout<T> where T : View {
    // responsible for laying out the sales order header
    // in different layouts depending on need: Grid, StackLayout, etc
    }
    
    ...
    // build the header dynamically and wherever the current
    //context requires (not in a fixed position in the XAML layout) 
    salesOrderLayout.Children.Add( getOrderHeaderLayout() );
    

    Abstractions as described here also facilitate MVVM, and various MVVM frameworks, and may even help to separate Views from their own mechanics. This would facilitate different MVVM Views being used for a single ViewModel, where the Views share common components. That seems extremely elegant to me. Hmmm, I think all still easily do-able with XAML but not as OOP as doing it with code.

    The note by @EasyGoingPat about conditional Debug-mode XAML resonated with me, and in the absence of the ability to do that in XAML, it's dirt-simple to do that in C#.

    I was REALLY impressed with @VincentH publishing https://github.com/VincentH-Net/CSharpForMarkup, and completely blown away by https://github.com/OYIon/LiveSharp. That was definitely compelling for me.

    But I'm still on the fence. I think it's helpful to be able to drag/drop widgets from the VS toolbox to get a quick view of the properties of layouts and fields. Using C# without XAML would feel awkward, losing the visual cues from the VS designer view, but LiveSharp replaces that. Since in many cases we need to manipulate the views from the code-behind anyway, it just seems more elegant to put the layout definition all in one place or another - in code.

    For now I think I will switch to putting most of my UI in C#, and use XAML only more for rapid prototyping and small components. I might start to template my layouts with standard references, structures, and binding. Then pull in the templates when I need specific top-level or nested layouts, and then build them upon one-another in the final content pages. The default development pattern we all start with, with "XAML First" doesn't seem to hold up when it comes to crafting an environment like that.

    I really hope this discussion continues - for others, see: https://www.google.com/search?q=xamarin+without+xaml

    Sunday, September 22, 2019 8:30 PM
  • User180523 posted

    @TonyG said: With XAML (also a thing with ASP.NET), we are also highly subject to the notion of having to ask for a widget/control/view by ID.

    Really? Where? Because none of our company's Xamarin.Forms apps do this. Ask... From where? The ViewModel? Because a ViewModel isn't supposed to be doing anything specific for a view or even know about if one or more views are using it for context.

    When you're building the component in C#, you don't need to ask XAML for a reference to that object - Same question... Why are you even getting the actual control on the UI? Across multiple applications our company we don't do this.

    Monday, September 23, 2019 9:35 AM