Category Archives: Uncategorized

Example on how to use static resource(xml) data in xaml and bind it with combo box

<XmlDataProvider x:Key="RuleOperators" XPath="Items">
                            <x:XData>
                                <Items xmlns="">
                                    <Item Label="-- Select --" Value=""/>
                                    <Item Label="Is Equal to" Value="="/>
                                    <Item Label="Is Not Equal to" Value="!="/>
                                    <Item Label="Is Less than" Value="&lt;"/>
                                    <Item Label="Is Less than or Equal to" Value="&lt;="/>
                                    <Item Label="Is Greater than" Value="&gt;"/>
                                    <Item Label="Is Greater than or Equal to" Value="&gt;="/>
                                </Items>
                            </x:XData>
                        </XmlDataProvider>

<ComboBox ItemsSource="{Binding Source={StaticResource RuleOperators}, XPath=*, Mode=OneTime}" SelectedValue="{Binding Value, UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="@Value"  DisplayMemberPath="@Label" />
Advertisements

Binding directly to a public property of a collection inside ViewModel

You create a WPF window in the application. You add the following code segment to the application.
public class ViewModel
{
public CollectionView Data { get; set; }
}
public class BusinessObject
{
public string Name { get; set; }
}
The DataContext property of the window is set to an instance of the ViewModel class. The Data property of
the ViewModel instance is initialized with a collection of BusinessObject objects. You add a TextBox control
to the Window. You need to bind the Text property of the TextBox control to the Name property of the
current item of the CollectionView of the DataContext object. You also need to ensure that when a binding
error occurs, the Text property of the TextBox control is set to N/A. Which binding expression should you
use?

A. { Binding Path=Data/Name, FallbackValue=’N/A’ }
B. { Binding Path=Data.Name, FallbackValue=’N/A’ }

I used to think that it’s Data.Name, since we intuitively feel the ‘.’ syntax is the correct way to dig deeper into an object. Actually, that’s not the case in this scenario. The object collection in the view model is not bound first to an items control like combobox. If that was the case, then inside each combo box item you could easily call Name directly and the binding would cascade correctly. Here, we are directly trying to get to second level of object hierarchy and therefore the way to do it is to use XPath style syntax: Data/Name, and this will grab the first item in the collection  and bind its Name property to our textbox’s text. Even, if you add 10 textboxes, all will still grab the first item with this syntax.

MEF Error: Activation error occured while trying to get instance of type

MEF Error: Activation error occured while trying to get instance of type <typename>, key “”
I had this error and tried various fixes. The thing that fixed it was removing the string parameter from the Export Attribute above the classname.
The following gave the error
[Export(“VM”)]
[PartCreationPolicy(CreationPolicy.Shared)]
public class VM
{
}

 

The following worked like a charm 🙂
[Export]
[PartCreationPolicy(CreationPolicy.Shared)]
public class VM
{
}

A bug with ViewModel first approach

I found something interesting last week.

I was using typical viewmodel first approach. Had a DataTemplate defined in my Resource Dictionary and a view referenced inside it. Then had a collection of typeof(viewmodel) bound to the itemscontrol on view(tab control in this case). All worked fine. Then suddently i noticed something. After creating few tabs, some textboxes on each tab were simply mirroring each other. So if i type “abcd” on one textbox on first tab, that same textbox on second tab was also showing “abcd” text. I found this weird because I always thought that when i add a new item in the collection from the viewmodel, it will create a new instance of the childviewmodel(which is bound to each item of the list) and hence, also create a new instance of the view. This was happneing. I checked ReferenceEquals() and they were indeed different object. So why was this happening as if they were the same objects?

I also checked that I was not registering them as Singletons in Unity.

Finally, we found the culprit. It was the missing bindings. It seems that with ViewModel first approach, you are supposed to make sure that all the controls on the view are bound to some property on the respective ViewModel. If not, then they will simply mirror each other and depict the behaviour i explained above.

I did one more test. I kept three textboxes on the view. First with binding, second without binding, and third with binding but no public property actually defined by that name on the view model. What i found is this:

  1. The first textbox with binding, behaved as expected. Each maintained its own state and didn’t interferce or influence any other controls on other views on seperate tabs
  2. The second textbox always mirrored with other views on the tab contor. Any view on a tab with that textbox will kind of sync up with same textboxe on same view on another tab
  3. The third texbox kind of behaved opposite of second. Because of missing valid bindings, no matter what you type, the moment you switch between tabs, the value will vanish on for same textbox on all views on all tabs

So make sure you don’t forget to bind all your controls on the view if you are using the ViewModel first approach. So this is a second issue with using ViewModel first apporach, the first being that the same viewmodel can’t be used for different views.

LINQ joins when working with huge datasets

This is more of a research based findings.
I was trying to create an object map. This were POCO and had to recursively create the childitems collection of the same type in a nested structure. So each object had a collection of its own type. I was using LINQ inside and had two simple joins which were joining three in-memory C# collections. These collections were created as to mirror database tables so that we can work with LINQ, instead of working with database queries, which is definitely faster.

The total number of records were more than 46000. What we found that LINQ joins were slowing down the whole process and took 75 seconds to build the whole hierarchical object tree. When I moved all the data from three tables and created one flat table, then it took less that 15 seconds to create the same object tree.

So this is for all to note that it is better and efficient to work with flat tables using LINQ instead of working with multiple normalised tables and joining them when working with huge data. For small set of data, the difference will be negligible and can be ignored.

Dynamically change style for SelectedItem of ComboBox

In this case, I wanted to set a DataTrigger to change the style of the selectedItem of combo box when the binding return a particular value. Sounds very simple, right? Well, it didn’t turn not as such. This is because the selectedItem style is kind of locked and also redraws only on SelectedItemChanged event.

What it means is if you are dynamically adding combobox in a list control like treeview, then after adding it with a particular style, if you want to change the style of selectedItem(or for that matter all items) in combo box when a certain value changes(or even on certain eventtrigger), that style gets applied but not displayed for selectedItem. You have to select another item from combo box to see the applied style. In other words, if i have all items as blue and when data changes for a property from true to false, I want all items to become red. Then they all will go read except that the selectedItem will stay blue. If you dropdown the list, then you can see that the selectedItem in the dropdown has also gone red but not in the “selected” state, it still blue as currently selected. If you select any other item, then the new item is red and you can then go back to the initial selectedItem, then it will also come red but without doing this exercise, the selectedItem will automatically not turn red.

I spent almost an hour trying to sort this out and finally found a way out. Instead of changing the entire datatemplate, we ended up defining a textbox in datatemplate for combobox and inside that datatemplate, we attached a converter to the texbblock to change the property data to a property value i.e. red color in this case. But i wasn’t so straighforward, we had to set the binding on the Foreground property of textblock(you can chose any other property here), then Set the path as DataContext.IsTrue (IsTrue) is the public property on each item object bound to each item of combo i.e. not on the parent viewmodel that has collection bound to the combo’s itemsource property. Then set the relative source to the AncesterType={x:Type ComboBox} and Mode=FindAncestor, this mapped back to the parent combo box i.e. one level up from the each item of combobox and then attach the convertor as well. The converter will then check the value, do the necessary custom work i.e. return a foreground colour red in this case which will be finally applied to the Foreground color where all this super complex properties are set to.