XAML without the .xaml.cs code behind files - wpf

I'm using WPF with the Model-View-ViewModel pattern. Thus, my code behind files (.xaml.cs) are all empty, except for the constructor with a call to InitializeComponent. Thus, for every .xaml file I have a matching, useless, .xaml.cs file.
I swear I read somewhere that if the code behind file is empty except for the constructor, there is a way to delete the file from the project altogether. After searching the net, it seems that the appropriate way to do this is to use the 'x:Subclass' attribute:
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit"
x:Class="MyNamespace.MyClass"
x:Subclass="UserControl"
d:DesignWidth="700" d:DesignHeight="500">
This does the following in the generated .g.cs file:
Removes the 'partial' class modifier on MyClass.
Adds the class 'UserControl' in to its subclass list.
Seems perfect. Indeed, if you still have the .xaml.cs file in the build, it no longer compiles because of the missing partial--so I'm thinking this must be correct. However, if I remove the superfluous file from the build and run, the control does not get initialized correctly (it is blank). This is, I presume, because InitializeComponent() is not getting called. I see InitializeComponent is not virtual, so it seems there would be no way for the base class to call it (short of using reflection).
Am I missing something?
Thanks!
Eric

As another option, if you don't want to go all the way to using DataTemplates, here is an alternate approach for UserControls:
Use the x:Code attribute to embed the constructor call in the XAML:
<x:Code><![CDATA[ public MyClass() { InitializeComponent(); }]]></x:Code>
Eric

If you follow Josh Smith's MVVM article, he uses DataTemplates for Views rather than user controls. If you put your DataTemplates into ResourceDictionaries, they don't have a code-behind at all. If you're not using the code-behind of your user control, doesn't that mean you could use a DataTemplate approach? If you do that, WPF will take care of binding your View to your ViewModel for you.

I had a discussion with a Windows Client team member at PDC about this, and right now, was told that there is no officially supported way to completely eliminate the code behind file. As you can see, you can get it to compile, but InitializeComponent() is never called, so the control doesn't get setup properly.
The x:Subclass attribute "usage is primarily intended for languages that do not support partial class declarations." It was not intended to allow this behavior (unfortunately).

If you are using caliburn micro you can effectively remove .xaml.cs, the framework takes care of initialization (i.e. if you are going with the view-model approach).
This is discussed https://caliburnmicro.codeplex.com/discussions/444250

Out of sheer curiosity, have you tried using this:
x:Subclass="Control"
By default, UserControls require the InitializeComponent() call, but defacto-standard Controls do not. I'd be interested to see if this works.
-Doug

Related

Does Window.DataContext and Window.Resource ObjectDataProvider conflict

I'm still getting comfortable with WPF, so this might be a silly question. I'm tracking the source of a tab control issue and discovered that I don't know the answer to the question in the title.
My Mvvm-Lite project template put the usual in the Windows opening tag:
DataContext="{Binding Source={StaticResource Locator}, Path=Main}"
And from somewhere else (I really don't remember) I have this handy static resource:
<ObjectDataProvider x:Key="src" ObjectType="vm:MainViewModel" />
While I'm troubleshooting my tab control issue (I won't bore you with those details here) I realized that I didn't know if these two ways of pointing to the view model confilicted in any way. Two separate instances of the view model? I don't think so cause the ViewModelLocator is holding a static reference to Main. Anyway, I just wanted to be sure that I haven't made a "greenie" mistake.
Thanks,
Jim
I am pretty sure that this is going to create two different instances. You can easily verify this by placing a breakpoint in the MainViewModel constructor and running your application in debug mode.
ObjectDataProvider was introduced before MVVM was popular. I would argue that many objects in WPF are kind of obsoleted by MVVM, because now we create these objects and properties in code in the ViewModel layer. In your case, I guess that you probably don't need the ObjectDataProvider, but can use the ViewModelLocator.Main everywhere instead.
Cheers,
Laurent

WPF Architecture Confusion RE: Routed Commands, Events, and Gestures

In learning WPF, I've been reading scads of books and web sites. One thing that seems to keep evading me is how we are supposed to properly wire up RoutedCommands. In one article, the author pointed out that the codebehind for your XAML files is supposed to contain nothing more than the call to InitializeComponent. I can get behind that. It makes the XAML file nothing more than a presentation document, and satisifies my unholy craving for separation of concerns.
On the other hand, every sample I've seen that addresses double-click events seems to want you to write code. It was my understanding that we wanted to get away from having repetitive code in the codebehind files (and, again, I'm all for that), so it seems to me that that's not the right way to do it. The same is true of menu commands, toolbar button clicks, and so forth.
Imagine, for instance, that I have a command to open a document. That command has to present the Open dialog, then open the document and cache it in the application state. (This application only allows you to work on one document at a time.) The user can invoke this command by either:
Choosing File->Open from the menu.
Typing Ctrl+O.
Clicking the Open button on the toolbar.
If I trust most of the sources on the Web, I have to write at least two Click event handlers that then invoke the command, polluting the codebehind file. That seems, to me, to defeat the purpose of having the Commands. I thought that I read somewhere that there was a way to bind the command to these things declaratively in XAML and it would do it for you, even disabling the command if it couldn't execute. But now I can't seem to find it, nor a decent example of how to do it.
Could someone please explain this to me? It's all starting to look like voodoo and shrapnel at this point.
The usual way to avoid codebehind with commands is to avoid RoutedCommands. In the various variations on the MVVM (Model-View-ViewModel) theme, people tend to use custom implementations of ICommand. They write a ViewModel class that is placed in the DataContext of the UI. This ViewModel exposes properties of type ICommand, and those command properties are connected to menu items, buttons and so on through data binding. (And it's usually just the one implementation of ICommand used over and over again - search the web for either RelayCommand or DelegateCommand or DelegatingCommand, and you'll see the pattern - it's basically ICommand as a wrapper around a delegate, with optional support for enabled/disabled.)
In this idiom, you almost never use the built-in commands like ApplicationCommands.Open. The only real use for those things is if you want focus-sensitive commands to be handled intrinsically by controls. E.g., the TextBox has built in command handling for Edit, Copy, Paste, and so on. This avoids the codebehind issue because it's a full custom control, and custom controls don't really have codebehind as such - they're all code. (The Xaml is actually in a completely separate object, the Template, and isn't really part of the control.) And in any case, it's not your code - you have a control that already knows how to support the command, so you can keep entirely within the Xaml here.
Command routing is interesting in that particular scenario because it lets you put one set of menu items associated with the various editing controls, and the routing system figures out which textbox (or whatever) will handle the command based on where the focus is. If that's not what you want, command routing probably isn't much use to you.
However, there's a bigger issue here of what to do when you find that you really do have to put code in the codebehind. Commands usually aren't an example of that scenario if you use custom ICommand implementations (although there's the odd exception), but the slightly more interesting user input events are. You mention double click, but also, if you're doing any kind of unusual interactivity you tend to want things like mouse up/down and so on.
In this case, the usual approach is to bite the bullet and put code in the codebehind, but you try to keep it to one line per event handler. Basically, your codebehind just calls into the relevant method on the viewmodel, and that's what really handles the event.
The lovely thing about that is it makes it really easy to write automated tests. Want to simulate the mouse entering a particular part of your UI? No need to mess around with unit test UI automation frameworks - just call the relevant method directly!
Commanding in WPF is quite cumbersome, but it does solve the problem of updating IsEnabled for you. Here's the canonical example. Step 1 is optional because there are a lot of built-in common commands to reduce the amount of boiler-plate.
Step 1. (Optional) Create your command in a static class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
namespace WpfApplication1
{
public static class Commands
{
public static RoutedCommand WibbleCommand = new RoutedUICommand
(
"Wibble",
"Wibble",
typeof(Commands),
new InputGestureCollection()
{
new KeyGesture(Key.O, ModifierKeys.Control)
}
);
}
}
Step 2: Declare command bindings in the xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Window.CommandBindings>
<CommandBinding
Command="{x:Static local:Commands.WibbleCommand}"
Executed="WibbleCommandExecuted"
CanExecute="WibbleCommandCanExecute"
/>
</Window.CommandBindings>
Step 3: Wire up your controls (menuitems, buttons etc)
The long binding here is to rectify the fact that Button by default won't use the command text.
<Button Command="{x:Static local:Commands.WibbleCommand}" Width="200" Height="80">
<TextBlock Text="{Binding Path=Command.Text, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}">
</TextBlock>
</Button>
Step 4: Implement handlers for Execute and CanExecute in codebehind
Careful with CanExecute! This will be called quite often, so try not to do anything expensive here.
private void WibbleCommandExecuted(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("Wibbled!");
}
private void WibbleCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = DateTime.Now.Minute % 2 == 0;
}

Can you view XAML as "regular" .net code (c#\vb.net)?

There are times when I find some example XAML that I want\need to do in code (c#\vb.net).
I assume at some point the XAML becomes code, or at least IL.
So my questions:
Am I correct in assuming that XAML is converted to IL? (or if not IL what does it become?)
If the above is correct, when does XAML become IL (or whatever it becomes)?
Is there some way to see the XAML in as "code"
Thanks.
No, XAML does not compile into IL, that gets done at runtime. The best way to think about it is as a way to compose an application from components.
For the majority of things you can replicate in C# what you do in XAML, however there is a small number of things that is available in XAML that's not in C# and vice versa. Charles Petzold at some point said that ostensibly, XAML looks like XML, but it's actually not, it's a language of its own.
For example this XAML code:
<Grid>
<TextBlock Text="Something" />
</Grid>
Is equivalent to the following C# code. This will get done in C# at runtime and short of setting a breakpoint in a particular component's constructor, there isn't much you can do to figure out what executes at runtime.
var grid = new Grid();
grid.Children.Add(new TextBlock{Text = "Something"});
I am sure there is a solution to your problem, but not as an answer to this particular question. Can you give more details on your problem and we can help you understanding it.
WPF and Silverlight treat XAML differently; neither convert XAML to IL. WPF's markup compiler converts XAML to a compiled form called BAML that is a binary version of the XAML. Silverlight leaves the XAML as plain text (compressd in the .XAP) and parses it at runtime.
Is there some way to see the XAML in
as "code"
If you are talking about the hierarchy of controls in xaml, then you may use myControl.Parent.
You can "see in code" how the controls in xaml are nested. You will also get/set their properties.

How to bind resources string to Xaml in Silverlight

How do you bind resources string to Xaml in Silverlight?
You need to add this reference to the App.xaml
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Then you need to add the string into the <Application.Resources> section
<sys:String x:Key="ResourceString">Resource String</clr:String>
Then all you need to do is refer to *{StaticResource ResourceString}
for example:
<TextBlock Text="{StaticResource ResourceString}"></TextBlock>
Been a while since this was asked and answered, I just wanted to add an additional answer as the first one is not entirely correct. I think he's asking for resources, aka. text written in .resx files. It doesn't make sense at all to add individual strings into the StaticResources collection in the application.
I blogged recently on how to simplify the way you work with resources in Silverlight, enabling both automatic update when the culture changes and a dependency property which gives you simpler syntax.
http://sondreb.com/blog/post/Simplifying-Text-Resources-in-Silverlight.aspx

WPF using custom RoutedUICommands or simple event handlers?

I was talking to someone today about picking a design pattern for how to handle logic in their WPF program and hoping that the SO community can help with further advice to make the decision easier. What factors in favour of commands outweigh the inconvenience?
I prepared a full sample along with some UML diagrams of the first two of three approaches:
Use Click event handlers on buttons and menus.
Use commands bound in XAML.
Use commands bound in code, with the XAML kept for pure GUI layout and styling.
The introductory course he'd been on and many of the books show simple Click event handlers as the natural way to connect logic to UI objects.
He was a bit stunned by the amount of overhead required to use commands with both the command being created in the code behind file:
public static readonly ICommand cmdShow2 = new RoutedUICommand(
"Show Window2", "cmdShow2",
typeof(TestDespatchWindow));
and then even more code in the XAML with the wordy way the command has to be identified and bound:
<Window x:Class="WPFDispatchDemo.TestDespatchWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:w="clr-namespace:WPFDispatchDemo"..>
<Window.CommandBindings>
<CommandBinding Command="{x:Static w:TestDespatchWindow.cmdShow2}"
Executed="OnShow2" />
</Window.CommandBindings>
<DockPanel>
<StackPanel Margin="0,8,0,0">
<Button x:Name="Show2EventBased"
Margin="10,2,10,2"
Click="OnShow2"
Content="Show2 via WPF Event"/>
<Button x:Name="Show2Command"
Command="{x:Static w:TestDespatchWindow.cmdShow2}"
Margin="10,2,10,2"
Content="Show2 via WPF"/>
</StackPanel>
</DockPanel>
</Window>
I can't (yet) claim to be a WPF expert so I may have painted things as more complex than they really are but my suspicion is that you can't simplify things much more than the above.
Edit:
I found an interesting 3-way comparison between DelegateCommand, RoutedCommand and Event.
Commands their advantages and disadvantages, you have to choose based on your situation,
I highly recommend you make that choice on a case basis, don't choose "the one true way" for the entire project.
For some cases the separation between sender and receiver and the ability to send commands using only XAML is a big advantage (for a good example look how the ScrollBar control template communicates with the control logic at http://msdn.microsoft.com/en-us/library/ms742173.aspx ).
In other cases commands can turn what would have been a 2 lines event handler into some impossible to follow monstrosity involving changing 4 separate places in the application (How should the ViewModel close the form? ).
The only reason is to have well know registry of commands. Means that events are likely to be private methods and I feel that they are tightly bonded to code of the window. At the same time Commands gives ability to keep implementation (event) and definition (Command) separately, you can even use another class (take a look on ApplicationCommands).
In addition, when I am doing my WPF work I use implementation of the ICommand(Command Pattern). All logic of the command goes to the Execute method. This helps me to keep separation of logic in more structured way witout overcomplication of the window code. With this option you can create commands on your model and therefore bind them witout noise. Take a look.
Create model.
public class Model
{
ICommand CloseMessagePopupCommand {get; set;}
}
Then assign Data Context
public MainWindow()
{
this.DataContext = new Model();
}
And use follwing XAML code.
<Button
Command="{Binding CloseMessagePopupCommand}"
Content="{StaticResource Misc.Ok}" />
I try to stay true to the command pattern that Mike refers to when developing WPF applications, using a combination of Andy's #2 and #3 approaches.
I can think of only one downside of commands in my view: only certain actions of certain UI elements invoke commands. One way to get around this is to have your event handler call the Execute method on a command. I think that commands provide a very good way to encapsulate execution logic. If you maintain a large piece of UI and implement it using a MVC/MVC/MVVM pattern, this becomes very apparent.
I encourage you to take a look at Dan Crevier's series on the DataModel-View-ViewModel pattern, in particular the section on Commands and Encapsulating Commands. Even if this pattern doesn't meet your needs, it gives a great overview of how you can encapsulate logic inside a separate class.
Other variations on ICommand seem to be a popular way to implement complex command structures.
Brian Noyes in his article on PRISM says
Routed commands in WPF are very powerful and useful, but they have some shortcomings when applied to a composite application. The first is that they are entirely coupled to the visual tree-the invoker has to be part of the visual tree, and the command binding has to be tied in through the visual tree. ... The second shortcoming is that they are tightly tied in with the focus tree of the UI and goes on to talk about the DelegateCommand and CompositeCommand which CAL (Prism) includes.

Resources