Skip to main content


Showing posts with the label DependencyObject

DependencyObject in ViewModelBase - Good or Bad?

First of all, a very-very Happy New Year to all my readers. If you are reading this post, then I’m assuming that you have a working experience of WPF using MVVM.  Don’t worry, I’m not going to re-write a huge post on what MVVM is and where to use it? This blog is very small which talks about one of the best practices any developer implementing MVVM should follow. Well, let me provide you the context first. Last week I was going through one of my colleagues’ code and noticed few interesting things in his ViewModelBase class: It was holding few Dependency properties  It was inheriting  DependencyObject  How it sounds to you? Good or … ?  Of course, that is not at all a good practice as ViewModelBase is the base class for all the ViewModels and is not supposed to contain such code. Well, this is not the only reason.  There are many other reasons which are making this implementation a BIG NO.  1 st Reason – A DependencyObject was never meant to be a Source of a bi

Better way to play sound file on WPF button click

Recently I was working on a XAML based application, in which my requirement was to play a sound (.wav file) whenever a given button is clicked. So, to achieve this, I wrote a below snippet: My above snippet worked but at the same time, I feel a noticeable delay in beep sound and that make me analyze further and write a blog post :) Now question is, why there is delay between button click and sound ??? Well, there is a simple concept behind it, which I missed while implementing above requirement :( Reason is, the event hierarchy.  Most of us might be aware that Click is a bubbling event, which means event will be fired from the control who initiated it. So, in our case, whenever button is clicked, it bubbles from button to window. And that's the reason, click event handler is executing before the window event is triggered, which is ultimately leading to delay. Now, how to handle this??? Method 1: Then I thought to write a preview event, which will be fired