Static verification of bindings - wpf

Or "how do you make sure all your bindings stay correct?"
(this is kinda lengthy, but bear with me, I tried to make it as short as I could)
Consider the following example:
<TextBox Name="tb" />
<TextBlock Text="{Binding Text.TheProp, ElementName=tb}" />
It is perfectly known at compile time that the binding is incorrect (i.e. the parser knows the type of element tb, and therefore, it knows the type of it's Text property, and therefore, it knows that TheProp doesn't exist).
Yet, this code will compile and run (although with a binding error message in debug output).
This behavior may come in very handy in some situations: no matter what exact type my data is, as long as it has appropriately named properties, I'm ok. Thus, we get sort of "declarative duck typing".
However, duck typing is not always a good thing.
Specifically, while using the MVVM pattern, I know (most of the time) the exact types of all my ViewModel objects. On the other hand, the models become more and more complex over time, which gets me worried about future refactoring: what if I decide to rename some properties, or, God forbid, put them in a separate aggregated object? What's going to happen with all my bindings then? Will I have to rake all XAML files by hand? And even without refactoring - what if I simply make a typo?
A similar problem is already solved in other places of XAML. If, for instance, you put an incorrect property name in Style/Setter/#Property, you get a compile time error.
TemplateBinding also provides such verification. Which is very handy.
So, ideally, I would love to see something like this:
ProductViewModel.cs:
public class ProductViewModel
{
public Name { get; set; }
public Price { get; set; }
}
ProductView.XAML:
<UserControl x:Class="Shopping.View.ProductView"
x:DataContextType="vm:ProductViewModel"
xmlns:vm="clr-namespace:Shopping.ViewModel"
... >
<TextBox Text="{Binding Name}" /> <!-- OK -->
<TextBox Text="{Binding Price}" /> <!-- OK -->
<TextBox Text="{Binding ABC}" /> <!-- Compile time error: there is no property ABC in ProductViewModel -->
</UserControl>
ShoppingCart.XAML:
<UserControl x:Class="Shopping.View.ShoppingCartView"
x:DataContextType="vm:ShoppingCartViewModel"
xmlns:vm="clr-namespace:Shopping.ViewModel"
... >
<ItemsControl ItemsSource="{Binding Products}"
ItemType="vm:ProductViewModel" > <!-- Static check happens here
ShoppingCartViewModel.Products must
implement IEnumerable<ProductViewModel> -->
<ItemsControl.ItemTemplate>
<DataTemplate DataType="vm:ProductViewModel">
<view:ProductView /> <!-- DataContext is known to be of correct type
because of DataTemplate.DataType property -->
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</UserControl>
But let's get back to reality. In reality, all that dreaming is just not going to happen in the near future.
However, I am sure I'm not the first person to have this problem.
So, finally, the question is: How do you make sure your bindings are correct? And that they stay that way?

How about static analysis of your Xaml performed as a post-build step?
As part of .Net 4, Microsoft released a new System.Xaml library to provide robust Xaml parsing and serialization support independent of WPF. They are now beginning to build all kinds of interesting things on top of it, some of which may help you out.
In the XamlToolkit, for example, you'll find the XamlDOM that enables you to do easy static analysis of Xaml files. And taking that a bit further, there's FxCop rules for XAML.
Of most interest is Rob Relyea's BindingFinder that has the explicit goal of type checking Bindings in Xaml. This requires that you have type hints in your Xaml, like the DataType attribute in a DataTemplate, or the the new d:DataContext attribute on your Views (which Blend uses to provide design-time data). It then uses the XamlDOM to check that everything matches up.
Update: Resharper 6 now provides intellisense for data bindings, and warnings if you get your property paths wrong.

As a practical matter, I've never found this to be a problem, at least when using the MVVM pattern. The view model only exists in support of the view. I'm not going to change one without changing the other. Refactoring the view model isn't going to break the bindings in the view because it makes no sense to refactor the view model for its own sake. You'll only refactor the view model when (and because) you're changing the design of the view.
The other reason that I don't have this problem is that I'm not developing the view model independently of Expression Blend. For all but the most trivial UIs, I build my view models using some kind of dependency injection so that I can create a test data source that's usable in Expression Blend. When I create bindings in Blend, I know right away whether or not I've done it right.
As with MVVM in general, doing this is an unbelieveable pain in the ass until you understand what you're doing and why. (This long blog post by Jonas Follesø gives a pretty good overview of how to use Ninject for this purpose, though there are no end of other frameworks you can use.) I'm sure that there are problems that I haven't uncovered yet with this methodology - above and beyond the problem that I've added DI frameworks and Expression Blend onto the heap of things that I need to understand to develop WPF applications.
Pablo Casals said that constant experimentation keeps the artist young. I don't feel young.

Related

wpf binding a TreeView to a SortedDictionary<string, List<Class>>

OK, once again, my Google-Fu isn't up to par and I would really appreciate a little guidance here.
I have a WPF app with multiple pages, one of which contains a TabControl, of which one of the tabs contains a grid, in which one of the columns contains a StackPanel with just two items on it: a Label and a TreeView. I have no need to update the TreeView once the content is obtained. The app uses MVVMLight (great toolkit!) to expose the data and said data is exposed in an mvvm (observable) property as it should be. I have checked and the data itself is available in correct form once I get to the point of setting the ItemsSource property so I know it's not the lack of data or the structure of the data itself. I have looked at all the entries on the web (at least the first 4 pages worth) matching the search terms "wpf treeview dictionary" and all articles come close, but don't get me to where I need to be. I'm missing something and what's worse, IntelliSense is even "helping" by providing the correct values for the xaml settings. So I know I'm close, but after two days of frustration, I'm throwing in the towel and asking for an assist.
So...to the meat of the problem: The data that the TreeView needs to display is in the form of SortedDictionary<string, List<ServerEntityNameMsSqlSvr>>. A ServerEntityNameMsSqlSvr class contains multiple properties, one of which is FullName. What I want the TreeView to display is the dictionary Key as the parent node and the FullName from each of the items in the List<ServerEntityNameMsSqlSvr>. You'd think that'd be simple, no? Not for me, the closest I can get is to display the Key of the dictionary, but either nothing for the children (best case) or throw an exception that stops the app with a null exception (worst case).
Here is the xaml I'm using (worst case):
<TreeView Grid.Column="0" ItemsSource="{Binding TableHierarchy}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Value}">
<TextBlock Text="{Binding Path=Key}"/>
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate DataType="awe:ServerEntityNameMsSqlSvr">
<TextBlock Text="{Binding FullName}"/>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
"TableHierarchy" is the MVVM property that exposes the data, it is declared as SortedDictionary<string, List<ServerEntityNameMsSqlSvr>>. The DataType "awe:ServerEntityNameMsSqlSvr" is a simple class with a few methods and properties, nothing special. One layer of inheritance, no interfaces. Of the properties that are available, I want to expose just the FullName, which is declared as public string FullName => _FullName(); Yep, it calls an overloaded method to build the full name but the result is a simple string (and the method call happens when the data is built, not a display time, iow, the values are already there, at least debugging to the setter shows that the content is correct.
Some of the solutions that I have researched suggest that the data type be changed to something other than a dictionary. In this case, that's not possible and given that the lists are, on occasion, quite large, I don't want to rebuild it into something else. This needs to work with the sorted dictionary as declared.
The xaml shown above is indeed correct, however, the gadget that supports the data (the methods in the ServerEntityNameMsSqlServer class) all need to not throw exceptions under any circumstances. In this case, one of the methods not directly involved with the author's code but used somewhere else in the framework (an overloaded call to "Equals" that was constructed to check individual property equality to determine the result) was throwing a null exception because a property wasn't filled in for the particular use case.
Difficult to find, but that was the cause.

MVVM Light UniversalConverter bool to Visibility

I'm trying to make a pair of TextBlocks toggle (one Visible, the other Collapsed and vice-versa) on a bound boolean.
I could use BooleanToVisibilityConverter for one but can't do a ! for the other so I'm trying to use MVVM Light's UniversalConverter which takes a lambda in the ConverterParameter.
Trouble is, I can't find any examples of the use and my attempts fail.
I've declared it in the XAML resources:
<Window.Resources>
<ex:UniversalConverter x:Key="UniversalConverter" />
</Window.Resources>
and then added this to the TextBlock:
<TextBlock Visibility="{Binding Path=ShowA, Converter={StaticResource universalConverter}, ConverterParameter='b=>b?Visible:Collapsed'}">A</TextBlock>
<TextBlock Visibility="{Binding Path=ShowA, Converter={StaticResource universalConverter}, ConverterParameter='b=>b?Collapsed:Visible'}">B</TextBlock>
This throws an exception in the XAML design windows: Unknown identifier 'Visible'.
I've also tried b=>b?Visibility.Visible:Visibility.Collapsed which is an example in the UniversalConverter's Convert method comment; that throws Unknown identifier 'Visibility'.
How do I add the references needed to the UniversalConverter?
Honestly, I never used the UniversalConverter class from the excellent MVVM Light toolkit framework, so I can't answer your specific question "how to make it work".
But in order to solve your actual issue, you can create your own BooleanToVisibilityConverter that allows inverting the mapping between true/false and Visible/Collapsed. See How do I invert BooleanToVisibilityConverter? for examples.
Personally I really would avoid to use the UniversalConverter for many reasons:
undocumented as you now know
forces to write programming logic in the XAML, which is not the primary goal of the XAML...
... forces to write C# line of code that cannot be debugged (at least for VS2010 + .Net 4), which means this converter is a wrong approach IMHO
It seems UniversalConverter has been removed since year 2013
http://blog.galasoft.ch/posts/2013/01/mvvm-light-v4-1-26-change-log/
BL0023.004, Remove UniversalConverter

Beginner - confused about binding and resources in WPF

I'm trying to learn WPF but I find it very difficult to understand bindings, the "resources" thing, and object creation.
My background is in C++/MFC and C#-Winforms.
My questions:
Most of the examples I see in XAML (in MSDN and in two other WPF books I've read) use StaticResource in the binding expression. Are these related in any way to static members? Or is this just a misleading name? When a reference is made to any object as a StaticResource, when is it instantiated?
As far as I can see StaticResources are used with "things" defined in the "Resources" section of the app/window/control etc.
Now, these Resources sections are very confusing to me.
What exactly are they? From my experience in MFC these were icons, strings, etc. However, judging by all the examples I've seen, in WPF these seem to be essentially a "dumping ground" for
(a) all kinds of global object definitions in markup (styles, data templates, etc)
(b) all kinds of global object instantiations in markup
Am I correct? This strikes me as very messy.
It essentially involves learning all sorts of semi-DSLs in XAML (for defining styles, for defining data templates, for creating objects etc), and sticking them together in the same place.
I keep thinking about something like editing the resource file (.rc) in MFC by hand. At least there the sections were well separated and the syntax for each resource was relatively simple.
To tie up the previous two questions: When I define an object instance in the Resources section, and later reference it from a StaticResource binding, when exactly is it instantiated?
MSDN says (in "How to: Make Data Available for Binding in XAML"):
one way you can make the object
available for binding is to define it
as a resource
However, this isn't very clear. What do they mean available? Do they mean created? Do they mean hooked up to the binding subsystem? And when exactly is that object created?
From playing around with a simple example I saw that WPF seems to create this object for me when it tries to attach the binding. And this is even more confusing.
EDIT:
After the clarification by karmicpuppet below, I'm still confused as to how this is connected to Binding.
Suppose I have in my resources:
<local:Person x:Key="MyPerson" Name="Title"/>
(where Person is a class with a property called Name) and then in the window I have:
<TextBlock Text="{Binding Source={StaticResource MyPerson}, Path=Name}"/>
1) What does this do? Does it goes through the same steps - searching for the resource and then applying it to the Text property? Does the MyPerson object gets created at the time of Window creation, or later?
2) Do I have to use the Binding mechanism to bind to the Name property? Can't I bind to it directly like you did above with myBrush? Why can't I do something like this?
<TextBlock Text="{StaticResource MyPerson, Path=Name}"/>
Is it just a short-sightedness on the part of the framework? I think I'm missing very big here, but I can't seem to understand what...
3) I tried using DynamicResource, but I am very confused about each step I took.
a) Added a DependencyObject with a DependencyProperty above my single Window class in code (is this DependencyObject necessary?)
public class SomeText : DependencyObject
{
public string Header
{
get { return (string)GetValue(HeaderProperty); }
set { SetValue(HeaderProperty, value); }
}
public static readonly DependencyProperty HeaderProperty =
DependencyProperty.Register("Header", typeof(string), typeof(SomeText), new UIPropertyMetadata(0));
}
b) Added an instance of it to the Windows.Resources (is this necessary with DynamicResource? MSDN seems to say no, but if so I can't figure out how to do the next step in XAML)
c) I tried both:
Text="{Binding Source={DynamicResource HeaderText}, Path=Header}"
Which gave me an exception, and
Text="{DynamicResource HeaderText}"
But I couldn't understand where to put the path to the Header property.
This is my 5th or so attempt to fiddle around with WPF lately, and each time I get stumped by this seemingly simple things which don't work. I've read 2 books and I really try to understand the MSDN articles, however they're of no help at all.
First, an overall comment:
WPF is hard to learn. It's hard to learn because there are several different fundamentally new concepts that you have to get your head around at the same time. The struggle that you're having right now is that you're trying to learn at least three different things at once:
How the XamlReader (and particularly markup extensions) deserializes XAML into objects.
How the FrameworkElement's resource dictionaries work.
How data binding works.
Something like this:
<TextBox Text="{Binding Source={StaticResource MyPerson}, Path=Name}"/>
is engaging (at least) three very different technologies at the same time. Those technologies are all designed to be as flexible as possible, which only makes them more confusing to the beginner. The idea that a binding source can be just about anything: that's hard to grasp. The idea that a markup extension is a special kind of serialization format that supports recursion: simple enough to understand in principle, but a little baffling when you first start working with real-world examples. The idea that a resource dictionary can contain just about anything, and that the resource searching algorithm essentially makes resources inheritable: again, pretty simple in concept, but easy to lose the thread of when you're trying to figure out data binding and XAML at the same time.
It's frustrating, because something that's conceptually simple - "I want to bind this control to a property of an object that I've created" - requires that you understand a great many things before you can actually express it in XAML.
The only solution is to be patient, and to make sure you understand things at the lowest level possible. When you see this:
{StaticResource MyPerson}
you should be able to think, "That's going to invoke the StaticResource markup extension handler, which retrieves an object from a resource dictionary using the key MyPerson when the XAML is deserialized.
It's extremely challenging at first. I've been developing software professionally for 35 years, and I've found WPF to be the most challenging technology platform that I've ever learned by a considerable margin. But all of this stuff is hard to learn because it's incredibly functional and flexible. And the payoff of learning it is huge.
To address a couple of issues that karmicpuppet didn't:
From my experience in MFC [resources] were icons, strings, etc.
That hasn't changed. You can still create resource files in WPF and load them into objects at runtime. There are lots of different ways of doing this - you can create resources in the resource editor and load them via the Properties.Resources object, you can add image files (for instance) to the project, have them compiled as resources, and load them using their URI, and there are plenty of other ways that I don't know about.
The resources available to FrameworkElements via their resource dictionaries are a different thing. Well, sort of. Here's an example:
<Window.Resources>
<Image x:Key="MyImage" Source="images/myimage.png"/>
</Window.Resources>
This creates an Image object and adds it to the Window's resource dictionary with a key of MyImage You can then reference that object via the StaticResource markup extension in XAML, or the FindResource method in code.
Setting the Source attribute on the Image element in XAML also makes the XamlReader use the ResourceManager to read the image data from the project's compiled resources at runtime when it creates the Image object.
In practice, this is nowhere near as confusing as it is when you're first learning WPF. I never get resources that ResourceManager loads and resources stored in resource dictionaries mixed up.
And when exactly is that object created?
Any object defined by a XAML element is created when the XamlReader reads the element. So this:
<Window.Resources>
<local:Person x:Key="MyPerson"/>
</Window.Resources>
instantiates a new Person object and adds it to the Window's resource dictionary with a key of MyPerson. It's exactly equivalent to doing this in the Window's code-behind:
AddResource("MyPerson", new Person());
So why don't you just do it in code-behind? Two reasons:
First, it's consistent. If you define all your resources in XAML, you only need to look in XAML files to find what your resources are. If you define them in both XAML and code-behind, you have to look in two places.
Second, the IDE knows about resources that you define in XAML. If you type
<TextBox Text="{Binding {StaticResource MyPerson}, Path=Name}"/>
in your XAML, the IDE will let you know if you haven't defined, somewhere in the hierarchy of resource dictionaries, a resource whose key is MyPerson. But it doesn't know about resources that you've added in code, and so even though the resource may actually be findable at runtime, the IDE will report it as a problem.
Think about it this way: all FrameworkElements (Windows, Buttons, other Controls, etc), as well as the Application object, contain a Dictionary of Resources. Whenever you define a resource in XAML as shown here:
<Window>
<Window.Resources>
<SolidColorBrush x:Key="myBrush" Color="Red"/>
<DataTemplate x:Key"myTemplate">
<!--Template definition here -->
</DataTemplate>
</Window.Resources>
</Window>
It's like doing something like this in code:
class Window
{
void Window()
{
this.Resources.Add("myBrush", new SolidColorBrush(Brushes.Red));
this.Resources.Add("myTemplate", new DataTemplate());
}
}
You can put all kinds of objects as Resources. Anything that you would like to re-use throughout your application, you can define it as a Resource.
Now, when you do use a "{StaticResource}" as follows:
<Button Background="{StaticResource myBrush}"/>
This is like telling WPF to search for the corresponding "myBrush" resource and apply it to the Background property. What will happen is WPF will first search the resource in the Button's resource dictionary, and if it's not found will search its parent, then its parent's parent, and so on up to the application's resources.
The "static" thing in "StaticResource" just distinguishes it from the other type of resource-lookup called "DynamicResource". The difference between the two is answered in this link.
When applied to Binding, it also works the same way. Say, for instance, you have the following resource in your XAML:
<local:Person x:Key="MyPerson" Name="Title"/>
and used it as:
<TextBlock Text="{Binding Source={StaticResource MyPerson}, Path=Name}"/>
In this case, what will happen is something like this:
Binding b = new Binding();
b.Source = FindResource("MyPerson");
b.Path = "Name";
[TextBlock].SetBinding(TextBlock.TextProperty, b);
Again, the "{StaticResource}" markup in the XAML tells WPF to search for the corresponding resource and set it as the value for the a property. In this case, the property is Binding's "Source" property.
That's the basics. Hope you find this helpful

General Design Question about data binding in WPF

I'm starting to use Binding in my WPF project and I'm actually confused about few things on the presentation side (XAML).
So I want to populate a TreeView with a List of Categories. I know how to write the right HierarchicalDataTemplate for my List of Category instances.
<HierarchicalDataTemplate ItemsSource="{Binding Path=ChildrenCategories}" DataType="{x:Type src:Category}">
<TextBlock Text="{Binding Path=Name}"></TextBlock>
</HierarchicalDataTemplate>
But what now I don't know is from where to get the list. I have here 2 solutions :
I got a Library Singleton class
which return me the right
arborescence, then I need to use an
ObjectDataProvider in my xaml which
would call the
Library.Instance.Categories method. (Which means that the controller has to be completely separated from the UI).
I got a Property ListCategories
in my page interactionLogic
(OpenUnit.xaml.cs), and bind the
tree with it.
I'm not sure about the purpose of the xaml.cs files, what are they made for? Is it normally used to store the properties (and act as a controller) or simply to have a back-end for the UI (for example get values from the UI?)?
In case the xaml.cs file is used as a controller, how do I bind my data to it, I've tried many solutions without success,my only success was with the use of static binding.
I would appreciate any comment or recommandation about UI and Logic Binding in WPF, hopefully I will get less confused.
Thanks in advance,
Boris
After reading this great article, I got a little bit less confused :
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
The article is about the Model View ViewController pattern, and how WPF integrates it. So it seems that xaml.cs files should be used as the ViewController here, and should hold the properties.
It actually make sense since it's not a good practice to mix the View and the Data, we want the designers should have a completely independant work to do.
Also for the solution 2) it is possible if you set the data context to the current file.

Silverlight - Paramterised resource values for Internationalisation

I'm running into a problem that seems to have no sensible / tractable solution that I am happy with. Silverlight and Internationalisation - a quagmire in the making.
I have a set of resource files that contain translated strings.
In the simple case, I can declare the language resource etc and bind the content / text of a value within the strongly typed resource. Thats fine - plenty of examples of that posted around.
A less simple case is that the strings can have a parameter, so I need to inject a value into the string for the display of it, which in itself can be a data binding.
The more complex scenario is a string with multiple parameters.
You can argue that the VM should provide this ability, but I am unhappy at that since it breaks the divide between the UX Designer and the Developer, requiring the developer to implement a property / method on the VM to support every string the UI requires.
For example : The designer decides after user feedback to add a custom tooltip with more information on it. The tooltip is done declaratively and combines a better explanation with values from the datacontext. The explanation is stored in the resources and the values used come from either an existing data context or an element to element binding.
If I have to run every string through the VM then the addition of something like this requires VM changes. Equally if the source of the parameters will be from other elements, then the VM is not necessarily in the position to provide the formatted string.
How have people got round / approached this issue?
A.
This question is more complex than I can answer fully, but if you want bindings to consider a specific localization you should set the Language property of your UI Container (maybe your top level UserControl class). After that all bindings should use your requested localization. Check out this article, which concerns WPF but uses techniques that appear to be applicable to Silverlight: http://www.west-wind.com/weblog/posts/796725.aspx
I don't know exactly what you want to do but you've got several solutions.
Create a new string in your VM and make it INotifyPropertyChanged-able
public string MyTranslatedString
{
get
{
return string.Format("{0} Someone", LocalizedResource.Hello;
}
};
And then listen for localization change events (from your application)
Create several text blocks and bind the localized items:
<TextBlock HorizontalAlignment="Stretch" Foreground="Black" Text="{Binding Path=Resource.CurrentlyLoggedInAs, Source={StaticResource LocalizedStrings }}" VerticalAlignment="Center" Margin="0,0,5,0" />
<TextBlock HorizontalAlignment="Stretch" Foreground="Black" Text="{Binding Path=Username}" VerticalAlignment="Center" Margin="0,0,5,0" />
<Button Commands:Click.Command="{Binding Path=LogOutCommand}" Commands:Click.CommandParameter="" Content="{Binding Path=Resource.LogOut, Source={StaticResource LocalizedStrings }}" />
You need to add, in your main app:
<Application.Resources>
<local:LocalizedStrings
xmlns:local="clr-namespace:Localization.Silverlight;assembly=Localization.Silverlight"
x:Key="LocalizedStrings" />
</Application.Resources>
These are the easiest approaches I came up with but I'm quite happy to have something providing me with something simpler.

Resources