WPF / MVVM - Extending ViewModel Functionality Via ValueConverters

by Dean 28. September 2011 18:54
In a Model-View-ViewModel (MVVM) project, the ViewModel can easily become a large and unwieldy piece of code. You can break this down by creating a hierarchy of ViewModels that exist in a parent-child relationship, or you can extend the functionality of an existing ViewModel via the use of ValueConverters. Here is a simple example of what I mean First, a simple ViewModel that doesn’t contain any functionality, just properties and an implementation of INotifyPropertyChanged for change notificat... [More]

Tags: , ,

C# | WPF | MVVM | DataBinding

WPF MVVM – Simple Property Rules Engine

by Dean 9. September 2011 19:47
I'm currently working on a large legacy WPF project where my ViewModels often have a large number of properties, and those properties have some complex inter-relationships that need to be reflected in the behaviour of the app,  via the ViewModels and XAML bindings. Specifically, some properties may need to support some of the following behaviours: 1) A property may need to invoke a change notification in the UI if a related property changes 2) A property may be a calculated value, and th... [More]

Tags: ,

C# | MVVM | WPF | XAML

WPF TreeView – SelectedItem Two Way Binding

by Dean 1. September 2011 07:30
Because the standard WPF TreeView implementation supports Virtualization it is unable to support two way bindings on its SelectedItem property as standard. This makes sense, because with Virtualization you may not have a container (TreeViewItem) available for any particular bound data item at the time you need it (to set its IsSelected property of the TreeViewItem  to ‘True’). The solution is to use attached properties to force the ItemContainerGenerator to create the necessary containers ... [More]

Tags: , , ,

Attached Properties | MVVM | WPF | XAML

Shuffle an IEnumerable - 1 Line of Code

by Dean 28. June 2011 11:12
At a recent contractor interview I was asked how I would shuffle the numbers 0 - 51 (representing a deck of cards). I had a reasonable stab at it, but I wondered if I could do it on a single line of Linq syntax. On the way to my next interview, I had my eureka moment: var random = new Random(Guid.NewGuid().GetHashCode()); var shuffledCards = Enumerable.Range(0, 52).Select(n => Tuple.Create(n, random.Next())).OrderBy(t => t.Item2).Select(t => t.Item1); Not bad ! Dean

Tags: , ,

C# | Linq

Linq – ‘Chunking’ Enumerable Data With New Extension Method – ‘SelectChunk’

by Dean 29. November 2010 07:58
A couple of times now I've needed to lazy-enumerate a large collection, but in ‘chunks’ – or to put it in another way, I've needed to bring data back from the collection in bite-sized batches. There currently isn't a Linq extension to support this (afaik), so I wrote one. It preserves the lazy-enumerating characteristics of most other Linq extensions, and seems to work very well. public static IEnumerable<IEnumerable<TResult>> SelectChunk<TSource, TResult>( this IEnu... [More]

Tags:

C# | Linq

WPF – Colour Picker Widget With Attached Properties

by Dean 21. November 2010 08:47
We can set the colour of any WPF control that supports it, but what about being able to specifically sett individual colour channels (RED, GREEN, BLUE, ALPHA) I've seen many solutions that contain complex custom controls, but one of the key philosophies of WPF is to reuse what you already have, and change the look or extend the functionality via control templates and the dependency system. Therefore, I have created a colour picker widget that uses only standard controls, and doesn't even chang... [More]

Tags: ,

Attached Properties | DataBinding | WPF | XAML

WPF – Loading Spinner Via MVVM and Attached Properties

by Dean 13. November 2010 14:47
When I used to write a lot of Ajax for ASP.NET (many years ago) I quite like the feature whereby you could disable the page and show a ‘loading spinner’ while waiting for an update in the page. This is a great feature to have in WPF, so I have created a ViewModel with a ‘loading’ switch (bool), and an attached property that creates and displays the animated spinner (for the duration of the switch flag being true) Firstly, we need a control template for a content control that will be our animat... [More]

Tags: ,

WPF | XAML | Animation

WPF - Modal Controls Via DispatcherFrame (Nested Message Pumps)

by Dean 12. November 2010 09:55
Lets say your new WPF gui has a button that loads confidential data. Lets then say that during the button's click handler you need to get some credentials from the user BEFORE continuing code execution within the handler. The usual approach would be to popup a modal window via Window.ShowDialog(), because the gui thread will block until the popup is closed (for getting credentials in this scenario) which is the desired behaviour. But what if you wanted to do something a bit more complex, using ... [More]

Tags: ,

C# | WPF | Dispatcher

MVVM – Simple Generic<T> Event Commands With Attached Properties

by Dean 10. November 2010 07:08
One of the challenges of MVVM is to favour command bindings over handling routed events, as currently all event handling must happen in the ‘code behind’ file rather than the ViewModel – which breaks the pattern. With WPF4 we get the new InputBindings feature, that allows us to hook-up mouse and keyboard gestures to commands, but this still doesn't solve all scenarios where event handling seems to be our only option. There are many elaborate and highly engineered strategies that I have seen to... [More]

Tags: , ,

WPF | Silverlight | MVVM | DataBinding | XAML | Events

Is It Nullable ?

by Dean 8. November 2010 16:42
Sometimes, you may have a scenario whereby you need to know if a value is a value type (say 'int'), or a nullable type (say 'int?'). Common sense suggests that we should easily be able to detect wether a type is nullable or not, but if you have a try, you'll see there are no obvious answers, or many unobvious ones either. The problem stems from the fact that if you query the type of a nullable instance it'll cause it to be boxed, and the boxing operation means that GetType() brings back the ty... [More]

Tags:

C#

LINQ - Dynamically Leverage IList<T> Functionality With VirtualList<T>

by Dean 1. November 2010 14:31
There are a lot of extension methods in the LINQ space that allow you to manipulate lists quickly and efficiently, but we may not always want to use an actual list to leverage the power of this functionality. confused - well, consider this code: Enumerable.Range(0, int.MaxValue).Aggregate(........) the line above is to run an aggregation function a very large number of times. This could be a candidate for task parallelism via the TPL, but doing the following actually has no effect Enumerab... [More]

Tags:

C# | Linq

Linq Trivia - Calculating PI with a single line of code

by Dean 1. November 2010 11:32
I recently had an interview where I was given the task of calculating the mathematical constant PI. I was going to do it in a single line of code (to show off my Linq prowess), but thought the interviewer would have considered me a bit of a geek, so I fleshed it out to his expectations. But heres the line anyway var pi = Enumerable.Range(0, 100000000).Aggregate(0d, (tot, next) => tot += Math.Pow(-1d, next)/(2*next + 1)*4); Not bad !! Dean

Tags:

Linq

WPF – Using Attached Properties For Animated Data Change Notifications

by Dean 29. October 2010 09:49
Working in the investment banking industry, we often need to feed live (changing) market data into our WPF controls, and often there is a requirement that certain movements (in value) are highlighted briefly so as to give a strong visual representation of data changes. The best way to do this (in my opinion) is to have the TextBlock representing the value ‘blink’ a different colour when the value changes. You would normally include rules that for example stipulate that a movement of more than 3... [More]

Tags: , ,

C# | DataBinding | Events | WPF | Animation

WPF – Easy INotifyPropertyChanged Via DynamicObject Proxy

by Dean 15. October 2010 07:53
There has been a big debate at the bank about how best to implement INotifyPropertyChanged on Model classes that need to support change notifications. None of the approaches seem entirely satisfactory, and here is a quick rundown of the main contenders: Default approach – hard-code string representations of the property name that’s changing –> this is the easiest approach, and the one that’s included in most documentation, but it can quickly introduce subtle binding errors in WPF if you ... [More]

Tags: , , ,

C# | DataBinding | MVVM | WPF | XAML

F# - Interacting With WPF Dispatcher Via F# Interactive Window

by Dean 8. October 2010 08:44
Heres an interesting scenario that was discussed with me by one of the quants in the front-office team yesterday. "Can I invoke a WPF Window/Control to popup from the FSI window in Visual Studio ?" - "Yes, thats easy I said".... "and then interact with it ASYNCHRONOUSLY via F# commands in the FSI window ?" - "hmmmm, I said" So the first bit is easy and has been done many times before with WPF and Winforms, and that is mainly to instantiate UI controls and popups from within Fsharp Interactive... [More]

Tags: , , ,

F# | Threading | WPF

WPF - Simple Error Notifications For Data Binding Expressions

by Dean 7. October 2010 14:19
One of the frustrating things about a large and complex XAML view in WPF, is that you are not often aware of errors in your data binding expressions. You may not even know there's an error, and if you do then you have to trawl through debugger outputs to try and find it. You could always use snoop, but surely theres a simpler way Here it is, in just a few lines of code:   public partial class MainWindow : Window { public MainWindow() { BindingErrorListener.Listen(m =... [More]

Tags: , ,

DataBinding | WPF

C# - Fast Parallel ConcurrentList<T> Implementation

by Dean 7. October 2010 09:59
The new Task Parallel Library (TPL) introduced in the .NET 4 framework simplifies many aspects of writing parallel code, without much of the necessary thread synchronisation logic that is usually required. One of the really nice aspects of TPL is the System.Collections.Concurrent namespace, which includes a number of collection classes that fully support multithreaded access and fast parallel access. The only glaring omission (in my opinion) is the absence of a ConcurrentList<T> class. S... [More]

Tags: , ,

C# | Threading | WPF

C# – Creating Reliable Complex Dictionary Keys Using Generic Tuples

by Dean 8. May 2010 12:56
As .NET developers we have all implemented dictionaries. Often, its a small dictionary with strings or Guids as the key – which is simple and robust. However, sometimes we need to do something a little more ‘serious’ and implement a dictionary that has a complex key consisting of a combination of values. In this case, it is extremely important that the type we use for the key has the following characteristics: Instances of the key’s type must be immutable, as changing their state once they ... [More]

Tags: , ,

C#

WPF MVVM – Simple ‘MessageBox.Show’ With Action & Func

by Dean 6. May 2010 08:08
In the MVVM world, things like message boxes (MessageBox.Show) and Dialogs (open file, save file etc), don't naturally fit. These popups are closely tied to the ‘View’ part of MVVM, but they can only really be invoked from the ‘ViewModel’ which will break the clean separation in MVVM. If you google this issue, you will find a wide range of elaborate solutions, many of which are significant engineering projects in their own right. I am a huge fan of implementing simple solutions wherever poss... [More]

Tags: ,

MVVM | C# | WPF | Unit Tests

WPF – DataContext Virtualization With Paged Services

by Dean 27. April 2010 21:51
Many WPF applications need to handle a very large data collections – maybe the users really need a million rows in their GridView control. The way we cope with this is to ‘virtualize’ the data, and have it available to your control on an ‘as needed’ basis. Most list controls in WPF (including the standard ListView/GridView) include the concept of a ‘viewport’ under the hood. A viewport is a virtual ‘window’ on the underlying data collection, which only requires the data currently being displaye... [More]

Tags: , ,

DataBinding | WCF | XAML | WPF

Lightweight ‘O/R Mapping’ in F# Interactive

by Dean 26. April 2010 21:15
I’ve been playing a lot with F# lately, particularly in the area of financial option modelling, which requires quite a lot of number crunching – a perfect scenario for tinkering around in F# interactive. However, I need to get data out of my data store, and use it to create collections of records, that represent the data that I need. This was becoming a little cumbersome, so I thought I’d create a little ORM function to do the trick open System.Data.SqlClient open Microsoft.... [More]

Tags: , , ,

F# | DataBinding

F# And MVVM – A Simple ViewModel

by Dean 12. April 2010 20:51
For many years, OOP abstractions and design patterns have been the cornerstones of my development methodology as a senior C# developer in investment banking. However, over the last year or so I have taken quite a shine to Microsoft’s new FP language (F#), not just because purely functional program code is concise powerful and elegant, but because the eclectic mix of functional and OOP paradigms in F# enable me to develop better, faster, stronger and more maintainable applications. In investmen... [More]

Tags: ,

DataBinding | F# | MVVM

A C# AIML Chatterbot – Artificial Intelligence In 500 Lines Of Code

by Dean 20. March 2010 21:28
I recently stumbled across an area of artificial intelligence programming called AIML ‘chatterbots’. These programs are interpreters for an XML based AI language called AIML. AIML and the code that processes it are the basis of the first and most famous chatterbot called A.L.I.C.E, where the founders and followers are infamous for promoting and winning the Loebner Prize in Artificial Intelligence. Among the available technologies, there are the usual suspects including implementations in PHP, P... [More]

Tags:

C# | AIML

Weak Events Without The Fuss With A ‘WeakReference’ Event Proxy

by Dean 28. February 2010 12:42
We all get clobbered at least once by memory leaks in our shiny new applications. One of the main causes of this is when objects that are expected to be garbage collected are not because we have not (or are unable) to unsubscribe them from the event handlers of longer living (static) objects. The de-facto solution is to implement Microsoft’s ‘WeakEventManager’, but it takes a lot of coding, and adds another layer of complexity to your applications. Wouldn’t it be great to do something a bit ea... [More]

Tags: ,

Events

Using CLR 4 Dynamics To Mock Bindable Objects in XAML

by Dean 3. February 2010 07:45
When I’m building prototypes in WPF or working on a GUI spike in an agile development team I often find it really unproductive to continuously switch between working in XAML (with my designer hat on), and working on the plumbing code (with my C# hat on). Wouldn't it be nice to be able to model my data in XAML, and seamlessly use it with XAML Binding expressions that’ll be valid once the ‘real’ data gets plumbed in. Well, thanks to the dynamic features in CLR v4 this is now a trivial task. Fir... [More]

Tags: , ,

DataBinding | XAML

Thread-Safe & Dispatcher-Safe Observable Collection for WPF

by Dean 1. February 2010 12:22
A common problem in WPF (& Silverlight) development is when you are working with multiple threads that need to change a collection that is a binding source and implements INotifyCollectionChanged. Basically, the standard ObservableCollection<T> will only allow updates from the dispatcher thread, which means you need to write a lot of code for the worker threads to marshal changes onto the main message pump via the dispatcher. This can be a bit tedious, so I recently wrote a collection... [More]

Tags:

DataBinding | C# | Threading

New Contract – New Opportunities

by Dean 29. January 2010 10:59
Today I was happy to sign myself up for a 6 month contract to deliver high performance WPF and Winforms GUI projects for a AAA investment bank’s ‘front-office’ trading team. The project will be very demanding and test my strong knowledge of multi-threaded WPF to the max :) This blog will therefore become more focussed on WPF, especially any interesting posts I can write on high-performance and multi-threading issues.   Happy days !! Dean

Tags:

Im Back !!

by Dean 21. January 2010 16:25
After a desperately busy year, where many things fell to the wayside (including this blog), I have returned to the world of Silverlight and WPF blogging. I hope over the coming weeks to make regular contributions to this blog   Dean

Tags:

Silverlight DataGrid – A Simple Pager Control

by Dean 11. February 2009 10:39
I love the fact that in Silverlight you can get all of your data onto the datagrid at the same time, rather than having to used a paged control in ASP.NET. However I’ve found that some users really want the data paging to remain, which means that I’ve got to roll may own DataGrid paging control. I know there are a few example out there, but I wanted to create a control that was a simple as possible but covered all of the major bases – so as little ‘code-behind’ as possible, and all the styling... [More]

Tags: ,

DataBinding | Silverlight

Generic Filter Control for Silverlight DataGrid

by Dean 6. February 2009 14:13
During the creation of a recent demo Silverlight project, I tasked myself with creating a generic (re-useable) filter control that I could use to filter rows in a Silverlight DataGrid. The control had to be lightweight, and work automatically with any object collection that the DataGrid was bound to – thus making it plug-and-play for any future uses. I’ve created a great starting point with this, by designing a set of inter-operating classes that have the following key features. The Filter... [More]

Tags: ,

Silverlight | DataBinding

Silverlight DataGrid – Prototyping Tip For Column Headers

by Dean 5. February 2009 14:58
Working in investment banking, I often get asked to create semi-functional prototypes of user interfaces, where the development methodology is all about speed and not about code-quality. Often these projects will be centred around the Silverlight DataGrid, and I want to get it up and running fast with whatever data object that needs to be used (the DataGrid will need to be bound to a collection of such objects). By default, a DataGrid for Silverlight will automatically generate columns, which ... [More]

Tags: ,

Silverlight | DataBinding

Enumeration Binding in Silverlight

by Dean 31. January 2009 10:57
A contractor colleague of mine (Phil Steel) had an interesting Silverlight problem yesterday. He wanted to populate a Silverlight ComboBox with an enumeration, and implement 2-way binding to a property on his Data class (i.e. binding his property to the ‘SelectedItem’ on the ComboBox. His requirements were as follows: The solution must have full design-time support in Expression Blend The code must give the developer an opportunity to create metadata for the enumeration that can be used... [More]

Tags: , ,

WCF | Silverlight | DataBinding

Fixed - Issues With WCF and Mixed VS/Blend Development

by Dean 25. January 2009 12:37
Some of you may have come across an issue when developing ‘fast and dirty’ demo apps in Silverlight that have a WCF backend service on the web application. When developing throwaway demo apps for clients, you need to take all of the shortcuts you can get, so I always use the ‘Add service reference’ feature of Visual Studio to add a service reference within my Silverlight app to the host ASP.NET service (not advisable for production-quality apps though). This is a great feature because as you ch... [More]

Tags: , ,

Silverlight | DataBinding | WCF

Silverlight and Related Blogs

by Dean 24. January 2009 14:25
I've spent some time tracking down Silverlight oriented (or related technology) blogs so I can keep on top of the community using FeedReader on my daily train journey into London. If anyone would like to add these blog references into their own RSS reader, you can download the OPML file below   Silverlight and Related Feeds (OPML File)   Please let me know if I've missed anyone, and I’ll keep this file up-to-date Dean

Tags: , ,

Silverlight

Generic IValueConverter for Silverlight or WPF

by Dean 24. January 2009 10:37
When using the GridView in ASP.NET it is very handy to be able to include a ‘FormatString’ attribute to bound columns and the like – enabling you to display those dates, currency values, numbers etc in a more readable form. I was surprised that Silverlight or WPF doesn't offer this out of the box, and I couldn't find any ‘obvious’ answers when I googled the subject, Therefore, I created a simple IValueConverter to achieve the same result. Here's the code for the converter: namesp... [More]

Tags: , ,

DataBinding | Silverlight

ObservableCollection Base Class With Expression Blend Designer Support – An Example Project

by Dean 19. January 2009 17:31
In my previous post showed how to create a lightweight collection class that can be used in expression blend enabling design-support for data bound control development. In this post, I thought I’d expand on my previous writings and actually create a sample project from beginning to end – demonstrating how easy it is to use this solution. Step 1 – Create Your Project (Programmers Job) In VS2008, create a Silverlight application project – Im going to call mine EmployeeInfo for the purpose of ... [More]

Tags: ,

Silverlight | DataBinding

ObservableCollection Base Class With Expression Blend Designer Support

by Dean 18. January 2009 23:54
One of the big issues for me with using Expression Blend for design in conjunction with VS2008 for the hard coding, is that you need to create at least test data loading stubs in the middle tier, delivered over WCF/WS in order visualize databound controls in the Silverlight app. This means that you often need to have everything ‘working’ on the data delivery backend before you can effectively design the visual elements, otherwise you’ll be trying to work with empty ListBoxes and DataGrids etc.... [More]

Tags: ,

Silverlight

Silverlight ‘Loading’ Spin Icon in XAML

by Dean 18. January 2009 15:36
When loading large object collections in Silverlight, there is enough of a time delay so that I need some kind of animated icon that indicates a ‘loading’ state. There were many such icons used when loading data via AJAX, which are basically animated Gif’s. As Gif’s aren't supported in Silverlight, I needed to create one. I decided therefore to create a design in Expression Design, and then animate it in Blend, with a little tidying up in VS2008. Im not sure how well it’ll perform with large n... [More]

Tags: ,

Silverlight

Coming Soon

by Dean 17. January 2009 16:19
This blog is under construction and will be coming soon

Tags:

RecentComments

Comment RSS
Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2012 Dean Chalk's Blog