WinUI3 DataGrid columns with x:Bind - xaml

Is there an MVVM way (using a ViewModel) to use x:bind in XAML for DataGrid columns (DataGridTextColumn, etc)?
All the code I've seen uses Binding not x:Bind.

To answer your question, unfortunately no. The DataGrid doesn't support x:Bind. There was a feature request a long time ago but I don't think it's going to be supported anytime soon.

Related

UWP MVVM XAML Dynamic UserControl Manager

I need help with a change of perspective.
I got stuck trying to approach UWP in a way I used to do in WPF regarding a MVVM pattern for managing UserControls dynamically.
I naturally tried to perform the same pattern in UWP but got stuck on various things like UWP not supporting 'x:Type' ...
Situation is; time to rethink this approach and look for a new direction. Seems I'm forced to abandon to use implicit binding in a similar fashion to the WPF pattern, using the Content property of a ContentPresenter and a VM property 'of type Object', which maintain a selected ViewModel. It was a simple and clean approach for matching up the correct View automagically with the VM set in ActiveViewModel.
the below was such a simple way of managing many views all over the place, odd MS not fixing this? But, back to the big Q: what now in UWP!?
<ContentPresenter Content="{Binding ActiveViewModel}">
<ContentPresenter.Resources>
<DataTemplate DataType="{x:Type local:OneViewModel}">
<local:OneView />
</DataTemplate>
<DataTemplate DataType="{x:Type local:TwoViewModel}">
<local:TwoView />
</DataTemplate>
</ContentPresenter.Resources>
</ContentPresenter>
What Shall I do instead of this!? Anyone found a new efficient way of doing it? I got stuck in my stubborn mind and need someone to kick my butt so I go forward. Getting to old to change, but due to this profession it seems I constantly have to. :)
Looking at the DataTemplate documentation, there's a paragraph explaining the situation which you are trying to figure out.
For advanced data binding scenarios, you might want to have properties
of the data determine which template should produce their UI
representations. For this scenario, you can use a DataTemplateSelector
and set properties such as ItemTemplateSelector to assign it to a data
view. A DataTemplateSelector is a logic class you write yourself,
which has a method that returns exactly one DataTemplate to the
binding engine based on your own logic interacting with your data. For
more info, see Data binding in depth.
Here, you have an example on how you can select distinct DataTemplate for items in a control such as a ListView based on defined conditions.
Your situation is a bit different from the one described above, but the solution should be within what is explained above.
Create a class which derives from DataTemplateSelector, and override the SelectTemplateCore methods exposed by it, where you define the logic of what DataTemplate should be selected for the specific presented object.
This Derived class should expose properties of type DataTemplate, which identify each single DataTemplate template object, you pretend to be able to choose from.
Just as in the example, you are probably better of by defining the DataTemplate resources on an higher level object, such as the Page itself.
Instantiate your DataTemplateSelector Derived class in XAML as a resource and set each of the properties exposed above of type DataTemplate to the analogous DataTemplate static resource.
Utilize the ContentTemplateSelector dependency property, by setting it your custom DataTemplateSelector.
With this logic, it should be possible to have your ContentPresenter decide correctly between which DataTemplate it should choose from, based on your required UI logic.

Why to avoid the codebehind in WPF MVVM pattern?

At the article, WPF Apps With The Model-View-ViewModel Design Pattern, the author who is Josh Smith said:
(1) In a well-designed MVVM architecture, the codebehind for most Views should be empty, or, at most, only contain code that manipulates the controls and resources contained within that view. (2) Sometimes it is also necessary to write code in a View's codebehind that interacts with a ViewModel object, such as hooking an event or calling a method that would otherwise be very difficult to invoke from the ViewModel itself.
My question is ,at the (1), why the empty codebehind is regarded as a a well-designed MVVM.(It sounds that the empty codebehind is always good.)
EDIT: My question is, as the following, why the approach like the AttachedCommandBehavior or the InvokeCommandAction is tried to avoid the codebehind coding.
Let me explain more detail.
As far as the (1) is concerned, I would think like the following situation as from the AttachedCommandBehavior. As the Border doesn't implement the ICommandSource for the MouseRightButtonDown, you cannot commonly bind the event and the ICommand, but can do with the AttachedCommandBehavior.
<!-- I modified some code from the AttachedCommandBehavior to show more simply -->
<Border>
<local:CommandBehaviorCollection.Behaviors>
<local:BehaviorBinding Event="MouseRightButtonDown"
Command="{Binding SomeCommand}"
CommandParameter="A Command on MouseRightButtonDown"/>
</local:CommandBehaviorCollection.Behaviors>
</Border>
OR
We can do this with the System.Windows.Interactivity.InvokeCommandAction.
<Border xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseRightButtonDown">
<i:InvokeCommandAction Command="{Binding SomeCommand}"
CommandParameter="A Command on MouseRightButtonDown"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Border>
BUT,
We use the following XAML and its codebehind having the Border_MouseRightButtonDown method, which is linked to the (2) Josh Simth said above.
<Border MouseRightButtonDown ="Border_MouseRightButtonDown"/>
I think using the codebehind as above is not bad just because the difference between these is only where binding a command or add event handler is.
What do you think about this?
why the empty codebehind is regarded as a a well-designed MVVM
Having a code-behind file which consists solely of a call to InitializeComponent() in its constructor means you have achieved purity - you have absolutely zero logic in your codebehind. You have not polluted your view with any code that rightfully belongs in the viewmodel or model. This means a couple of things:
the viewmodel (and model) is easier to test in isolation
you have achieved a good level of loose coupling, which has excellent benefits from a maintenance and extensibility perspective
The benefits really become noticeable when you have to change your UI, i.e. you switch from using a ListView to a DataGrid, or you change from using the standard Microsoft controls to using some other vendor's.
As mentioned though, it is sometimes impossible to avoid a little code in the code-behind file. What you should ensure is that the code you do have is purely UI related. As an example, if you have ComboA and ComboB, and ComboB is set in response to the selection in ComboA, then setting the SelectedIndex of ComboB from the view is fine, but setting the Items or the SelectedItem of ComboB is not - those properties are both data related and should be specified via binding to the viewmodel. The SelectedIndex property is directly visual related and somewhat independent of the actual data (and it is irrelevant to the viewmodel).
If you do access the viewmodel from code-behind in the view, you should try and do it via an interface. This means your viewmodel is injected or given to the view as an interface. (Note that the binding subsystem doesn't know or care about the interface, it will continue to bind in its normal way. What this achieves is better code, with less tight coupling). The way I code it, the viewmodel has no idea that a view exists, and the view only knows about the viewmodel as an interface.
One thing to remember though is that MVVM is a pattern, and a pattern is simply a recipe or prescription for achieving a certain result in a certain situation. It shouldn't be treated as a religion, where non-believers or non-conformers are going to go to some purgatory (although adherence to the pattern is good if you want to avoid the purgatory of maintenance hell and code smell).
If you want an excellent example of how this particular pattern helps, try writing a few reasonably complicated screens in ASP.Net, and then write the same in WPF or Silverlight, and note the difference.
Edit:
let me answer some of your questions, I hope it helps....
the viewmodel's (model of view) role , in my view, has UI logic and state of a view
The viewmodel should never have any UI logic or "view state" in it. For the purposes of this explanation, I would define view state as scroll position, selected row index, selected index, window size, etc. None of those belong in the viewmodel; things like SelectedIndex are specific to the way the data is shown in the UI (if you change the sort order of a DataGrid then the SelectedIndex can change, even though the SelectedItem is still the same). In this particular case, the SelectedItem can be bound to the viewmodel, but the SelectedIndex shouldn't.
If you need to keep track of UI session type info them then you should come up with something generic (for example, I have persisted view state before by saving important stuff into a KeyValuePair list) which is then "saved" with a call to the viewmodel (via the interface I mentioned previously). The view has no idea how the data is being saved, and the viewmodel has no idea the data is coming from a view (it has simply exposed a call through its interface).
and the view's role is displaying some contents and synchronizing the viewmodel(having databinding code)
Yes, the view's responsibility is simply to visually display data presented by the viewmodel. The viewmodel gets the data from the model (the model is responsible for making database calls or WCF webservice calls, this will usually be done via a "service", but that is a whole other discussion). The viewmodel can then shape or manipulate the data, i.e. it may get a list of all customers, but only expose a filtered version of that list (maybe the current customers) in a public property which the view can then bind to.
If the data is to be manipulated into something visual (a common example is an enum value being translated into a color), then the viewmodel still only has the enum value(s), and the view still binds to that value, but the view also uses a converter to translate the pure data to a visual representation. By using the converter the viewmodel has still avoided doing anything UI related, and the view has avoided any real logic.
The MVVM can split code and page design completely; coders just care about coding and designers only care about design. But:
I've never seen any designer who using Blend or understanding XAML.
Almost all XAMLs are written by coder himself.
There is nothing inherently bad in code-behind. For simple cases, it's fine to have it. However, UI logic can get difficult to manage in many scenarios. Encapsulating that logic in attached behaviors and view models allows us to isolate the variables (and test them) so that it's easier to comprehend and maintain.
If testability is a concern, the more of your UI logic that you can encapsulate in viewmodels and attached behaviors, the more you you will be able to verify without resorting to UI testing. (While it doesn't eliminate the need for UI Testing altogether, it does provide a first level of verification before engaging in UI Testing which will be more time/resource intensive.
I think the quoted section refers to the way data is visualized. I think they mean you should not write code in code behind that is, for example, related to how or where the data is displayed (for example something like: label1.Text = ...). Doing things like that using bindings makes it easier to separate design and code (what happens if you need the data to be displayed in a text box named "tbTest" in a later version? You'd have to change your code behind).
They are not saying that you shouldn't have any code in code behind - they are just saying that in an ideal world, you'd only react to events or process data that could not otherwise be processed.
At least that's what I understand from the section you quoted.
The MVVM pattern is powerful but I find it too 'Purist'. I can see benefit is having the code behind handle all the commands and properties in the view while the ViewModel is concerned with any translation to business model properties.
A benefit of this is that if you wish to change the user UI, perhaps from desktop to browser it is likely to be just replacing the View and its code behind.
Just my thoughts!!

Implicit DataTemplate equivalent for Silverlight + Prism

I'm building an Silverlight application which consists of a grid containing multiple different widgets. Each widget is implemented as a ViewModel class which are then binded to grid.
With WPF I'd use implicit DataTemplates to bind certain ViewModel to a certain View. But since Silverlight doesn't support this feature I'm a bit stuck.
So far I've only thought of implementing some sort of global DataTemplateSelector to which each Prism module would register matching ViewModel and View pairs at startup. Then I could use Unity to inject this selector to grid and achieve what I want but this doesn't feel like the best way to do it.
Any ideas how should I do this?
I did some more googling and found few articles about TemplateContentControl (e.g. http://blogs.microsoft.co.il/blogs/arielbh/archive/2010/10/24/how-to-develop-mvvm-silverlight-applications-with-prism.aspx) and after some testing it seems to be just what I was looking for.
Check out the DataTemplateSelector for Silverlight.
Read about it more here.

Dojo Grid Template

In asp.net the DataGrid supports templates. You can provide your own template and have the grid fill the data in your template.
With Dojo Grid, it seems like I can't make my own template outside of the the rigid simplistic cell style grid that Dojo provides.
Does anyone know a way to use a custom template with Dojo Grid? Specifically, with Dojo you're forced to use a cell that corresponds to a data item. I'm looking to use a table as a template with any styling that I choose (rows,columns,rowspans,colspans, more than one data items in a single cell, etc).
Any clues please?
Thanks
Firstly, it sounds like everything you want is available by customizing the grid. You can do nesting of cells and even have things like Filtering Selects in rows. Unfortunately the docs on this are not awesome so it takes Googling and trial and error if you want very customized features.
Secondly, because of the OO nature of Dojo you can always use inheritance to create mixes of various widgets. Specifically the _templated class allows you to specify an HTML template for your widget, which themselves can included templated widgets.
If that sounds non-trivial, you're right, which is why I would suggest digging deeper into the Enhanced grid and probably open up the code before trying to write something yourself.
I can tell you that I struggled getting it working correctly, but I have hence been pleasantly surprised by features that I needed that I thought I would need to build myself but were built into the grid.

XAML tag list reference

As the question suggests I'm simply looking for a XAML tag list reference. I've banged the obvious queries in Google/SO but not found what I am looking for yet. Any useful links welcome.
There's a WPF Binding Cheatsheet and another XAML for WPF Cheatsheet which might help, but really the "tags" in XAML are just the properties of the classes.
There isn't such a thing as a xaml tag list.
XAML is just a declarative way to instantiate .Net classes. Class names are elements in XAML and properties on the class are attributes or attribute elements using dot notation.
Tags in XAML only mirror the types in one or more assemblies that are bound to a particular XAML namespace.
There are however a specific set of elements that are specific to XAML in itself and are not related to any particular .Net assembly, those are usually in the x: namespace, more info here: XAML Namespace (x:).
There is no such thing as the XAML tag list since XAML is an open system.
There are, however, standard vocabularies. Rob Relyea's Blog is a good place to keep track of the standardization around these vocabluaries. For example, this is an entry for the Silverlight XAML vocabulary.
With WPF the XAML elements map to the classes like StackPanel. MSDN seems to give XAML examples for many of the controls.
There are XAML-specific conventions about representing things like complex properties and bindings. However, there is no definitive list of XAML tags. XAML tags are actually mapped to WPF objects. For example, <Button> is just a XAML representation of the System.Windows.Controls.Button class and the attributes allowed on the <Button> tag are the public properties of the Button class.
There should be several WPF cheatsheets available soon on http://www.devsheets.com (since around September 2011) ... You can download it there, and also buy printed versions with more detailed information on them (not all content fits in publicly available pdf, because pdf would not be readable if printed on paper without high quality print ... that is why we also decided to sell high quality laminated cheatsheet prints in addition to their free versions)