EzDevInfo.com

mvvm interview questions

Top mvvm frequently asked interview questions

INotifyPropertyChanged vs. DependencyProperty in ViewModel

When implementing the ViewModel in a Model-View-ViewModel architecture WPF application there seem to be two major choices how to make it databindable. I have seen implementations that use DependencyProperty for properties the View is going to bind against and I have seen the ViewModel implementing INotifyPropertyChanged instead.

My question is when should I prefer one over the other? Are there any performance differences? Is it really a good idea to give the ViewModel dependencies to WPF? What else do I need to consider when make the design decision?


Source: (StackOverflow)

What framework for MVVM should I use? [closed]

I am developing an application with the MVVM model, but I have reached a point where I need to choose which framework to use.

Among the possible options are:

  • MVVM Toolkit
  • MVVM Foundation
  • WPF Application Framework (WAF)
  • Light MVVM
  • Caliburn
  • Cinch
  • Prism

In your experience, which is better?


Source: (StackOverflow)

Advertisements

Firing a double click event from a WPF ListView item using MVVM

In a WPF application using MVVM, I have a usercontrol with a listview item. In run time, it will use databinding to fill the listview with a collection of objects.

What is the correct way to attach a double click event to the items in the listview so that when an item in the list view is doubleclicked, A corresponding event in the view model is fired and has a reference to the item clicked?

How can it be done in a clean MVVM way i.e. no code behind in the View?


Source: (StackOverflow)

How to architecture a webapp using jquery-mobile and knockoutjs

I would like to build a mobile app, brewed from nothing more but html/css and JavaScript. While I have a decent knowledge of how to build a web app with JavaScript, I thought I might have a look into a framework like jquery-mobile.

At first, I thought jquery-mobile was nothing more then a widget framework which targets mobile browsers. Very similar to jquery-ui but for the mobile world. But I noticed that jquery-mobile is more than that. It comes with a bunch of architecture and let's you create apps with a declarative html syntax. So for the most easy thinkable app, you wouldn't need to write a single line of JavaScript by yourself (which is cool, because we all like to work less, don't we?)

To support the approach of creating apps using a declarative html syntax, I think it's a good take to combine jquery-mobile with knockoutjs. Knockoutjs is a client-side MVVM framework that aims to bring MVVM super powers known from WPF/Silverlight to the JavaScript world.

For me MVVM is a new world. While I have already read a lot about it, I have never actually used it myself before.

So this posting is about how to architecture an app using jquery-mobile and knockoutjs together. My idea was to write down the approach that I came up with after looking at it for several hours, and have some jquery-mobile/knockout yoda to comment it, showing me why it sucks and why I shouldn't do programming in the first place ;-)

The html

jquery-mobile does a good job providing a basic structure model of pages. While I am well aware that I could have my pages to be loaded via ajax afterwards, I just decided to keep all of them in one index.html file. In this basic scenario we are talking about two pages so that it shouldn't be too hard to stay on top of things.

<!DOCTYPE html> 
<html> 
  <head> 
  <title>Page Title</title> 
  <link rel="stylesheet" rel='nofollow' href="libs/jquery-mobile/jquery.mobile-1.0a4.1.css" />
  <link rel="stylesheet" rel='nofollow' href="app/base/css/base.css" />
  <script src="libs/jquery/jquery-1.5.0.min.js"></script>
  <script src="libs/knockout/knockout-1.2.0.js"></script>
  <script src="libs/knockout/knockout-bindings-jqm.js" type="text/javascript"></script>
  <script src="libs/rx/rx.js" type="text/javascript"></script>
  <script src="app/App.js"></script>
  <script src="app/App.ViewModels.HomeScreenViewModel.js"></script>
  <script src="app/App.MockedStatisticsService.js"></script>
  <script src="libs/jquery-mobile/jquery.mobile-1.0a4.1.js"></script>  
</head> 
<body> 

<!-- Start of first page -->
<div data-role="page" id="home">

    <div data-role="header">
        <h1>Demo App</h1>
    </div><!-- /header -->

    <div data-role="content">   

    <div class="ui-grid-a">
        <div class="ui-block-a">
            <div class="ui-bar" style="height:120px">
                <h1>Tours today (please wait 10 seconds to see the effect)</h1>
                <p><span data-bind="text: toursTotal"></span> total</p>
                <p><span data-bind="text: toursRunning"></span> running</p>
                <p><span data-bind="text: toursCompleted"></span> completed</p>     
            </div>
        </div>
    </div>

    <fieldset class="ui-grid-a">
        <div class="ui-block-a"><button data-bind="click: showTourList, jqmButtonEnabled: toursAvailable" data-theme="a">Tour List</button></div>  
    </fieldset>

    </div><!-- /content -->

    <div data-role="footer" data-position="fixed">
        <h4>by Christoph Burgdorf</h4>
    </div><!-- /header -->
</div><!-- /page -->

<!-- tourlist page -->
<div data-role="page" id="tourlist">

    <div data-role="header">
        <h1>Bar</h1>
    </div><!-- /header -->

    <div data-role="content">   
        <p><a rel='nofollow' href="#home">Back to home</a></p> 
    </div><!-- /content -->

    <div data-role="footer" data-position="fixed">
        <h4>by Christoph Burgdorf</h4>
    </div><!-- /header -->
</div><!-- /page -->

</body>
</html>

The JavaScript

So let's come to the fun part - the JavaScript!

When I started to think about layering the app, I have had several things in mind (e.g. testability, loose coupling). I'm going to show you how I decided to split of my files and comment things like why did I choose one thing over another while I go...

App.js

var App = window.App = {};
App.ViewModels = {};

$(document).bind('mobileinit', function(){
    // while app is running use App.Service.mockStatistic({ToursCompleted: 45}); to fake backend data from the console
    var service = App.Service = new App.MockedStatisticService();    

  $('#home').live('pagecreate', function(event, ui){
        var viewModel = new App.ViewModels.HomeScreenViewModel(service);
        ko.applyBindings(viewModel, this);
        viewModel.startServicePolling();
  });
});

App.js is the entry point of my app. It creates the App object and provides a namespace for the view models (soon to come). It listenes for the mobileinit event which jquery-mobile provides.

As you can see, I'm creating a instance of some kind of ajax service (which we will look at later) and save it to the variable "service".

I also hook up the pagecreate event for the home page in which I create an instance of the viewModel that gets the service instance passed in. This point is essential to me. If anybody thinks, this should be done differently, please share your thoughts!

The point is, the view model needs to operate on a service (GetTour/, SaveTour etc.). But I don't want the ViewModel to know any more about it. So for example, in our case, I'm just passing in a mocked ajax service because the backend hasn't been developed yet.

Another thing I should mention is that the ViewModel has zero knowledge about the actual view. That's why I'm calling ko.applyBindings(viewModel, this) from within the pagecreate handler. I wanted to keep the view model seperated from the actual view to make it easier to test it.

App.ViewModels.HomeScreenViewModel.js

(function(App){
  App.ViewModels.HomeScreenViewModel = function(service){
    var self = {}, disposableServicePoller = Rx.Disposable.Empty;

    self.toursTotal = ko.observable(0);
    self.toursRunning = ko.observable(0);
    self.toursCompleted = ko.observable(0);
    self.toursAvailable = ko.dependentObservable(function(){ return this.toursTotal() > 0; }, self);
    self.showTourList = function(){ $.mobile.changePage('#tourlist', 'pop', false, true); };        
    self.startServicePolling = function(){  
        disposableServicePoller = Rx.Observable
            .Interval(10000)
            .Select(service.getStatistics)
            .Switch()
            .Subscribe(function(statistics){
                self.toursTotal(statistics.ToursTotal);
                self.toursRunning(statistics.ToursRunning); 
                self.toursCompleted(statistics.ToursCompleted); 
            });
    };
    self.stopServicePolling = disposableServicePoller.Dispose;      

    return self; 
  };
})(App)

While you will find most knockoutjs view model examples using an object literal syntax, I'm using the traditional function syntax with a 'self' helper objects. Basically, it's a matter of taste. But when you want to have one observable property to reference another, you can't write down the object literal in one go which makes it less symmetric. That's one of the reason why I'm choosing a different syntax.

The next reason is the service that I can pass on as a parameter as I mentioned before.

There is one more thing with this view model which I'm not sure if I did choose the right way. I want to poll the ajax service periodically to fetch the results from the server. So, I have choosen to implement startServicePolling/*stopServicePolling* methods to do so. The idea is to start the polling on pageshow, and stop it when the user navigates to different page.

You can ignore the syntax which is used to poll the service. It's RxJS magic. Just be sure I'm polling it and update the observable properties with the returned result as you can see in the Subscribe(function(statistics){..}) part.

App.MockedStatisticsService.js

Ok, there is just one thing left to show you. It's the actual service implementation. I'm not going much into detail here. It's just a mock that returns some numbers when getStatistics is called. There is another method mockStatistics which I use to set new values through the browsers js console while the app is running.

(function(App){
    App.MockedStatisticService = function(){
        var self = {},
        defaultStatistic = {
            ToursTotal: 505,
            ToursRunning: 110,
            ToursCompleted: 115 
        },
        currentStatistic = $.extend({}, defaultStatistic);;

        self.mockStatistic = function(statistics){
            currentStatistic = $.extend({}, defaultStatistic, statistics);
        };

        self.getStatistics = function(){        
            var asyncSubject = new Rx.AsyncSubject();
            asyncSubject.OnNext(currentStatistic);
            asyncSubject.OnCompleted();
            return asyncSubject.AsObservable();
        };

        return self;
    };
})(App)

Ok, I wrote much more as I initially planned to write. My finger hurt, my dogs are asking me to take them for a walk and I feel exhausted. I'm sure there are plenty things missing here and that I put in a bunch of typos and grammer mistakes. Yell at me if something isn't clear and I will update the posting later.

The posting might not seem as an question but actually it is! I would like you to share your thoughts about my approach and if you think it's good or bad or if I'm missing out things.

UPDATE

Due to the major popularity this posting gained and because several people asked me to do so, I have put the code of this example on github:

https://github.com/cburgdorf/stackoverflow-knockout-example

Get it while it's hot!


Source: (StackOverflow)

MVVM in WPF - How to alert ViewModel of changes in Model... or should I?

I am going through some MVVM articles, primarily this and this.

My specific question is: How do I communicate Model changes from the Model to the ViewModel?

In Josh's article, I don't see that he does this. The ViewModel always asks the Model for properties. In Rachel's example, she does have the model implement INotifyPropertyChanged, and raises events from the model, but they are for consumption by the view itself (see her article/code for more detail on why she does this).

Nowhere do I see examples where the model alerts the ViewModel of changes to model properties. This has me worried that perhaps it's not done for some reason. Is there a pattern for alerting the ViewModel of changes in the Model? It would seem to be necessary as (1) conceivably there are more than 1 ViewModel for each model, and (2) even if there is just one ViewModel, some action on the model might result in other properties being changed.

I suspect that there might be answers/comments of the form "Why would you want to do that?" comments, so here's a description of my program. I'm new to MVVM so perhaps my whole design is faulty. I'll briefly describe it.

I am programming up something that is more interesting (at least, to me!) than "Customer" or "Product" classes. I am programming BlackJack.

I have a View that doesn't have any code behind and just relies on binding to properties and commands in the ViewModel (see Josh Smith's article).

For better or worse, I took the attitude that the Model should contain not just classes such as PlayingCard, Deck, but also the BlackJackGame class that keeps state of the whole game, and knows when the player has gone bust, the dealer has to draw cards, and what the player and dealer current score is (less than 21, 21, bust, etc.).

From BlackJackGame I expose methods like "DrawCard" and it occurred to me that when a card is drawn, properties such as CardScore, and IsBust should be updated and these new values communicated to the ViewModel. Perhaps that's faulty thinking?

One could take the attitude that the ViewModel called the DrawCard() method so he should know to ask for an updated score and find out if he is bust or not. Opinions?

In my ViewModel, I have the logic to grab an actual image of a playing card (based on suit,rank) and make it available for the view. The model should not be concerned with this (perhaps other ViewModel would just use numbers instead of playing card images). Of course, perhaps some will tell me that the Model should not even have the concept of a BlackJack game and that should be handled in the ViewModel?


Source: (StackOverflow)

Good or bad practice for Dialogs in wpf with MVVM?

I lately had the problem of creating add and edit dialogs for my wpf app.

All I want to do in my code was something like this. (I mostly use viewmodel first approach with mvvm)

ViewModel which calls a dialog window:

 var result = this.uiDialogService.ShowDialog("Dialogwindow title goes here", dialogwindowVM);

 ... do anything with the dialog result...

How does it work?

First, I created a dialog service:

public interface IUIWindowDialogService
{
    bool? ShowDialog(string title, object datacontext);
}

public class WpfUIWindowDialogService : IUIWindowDialogService
{
    public bool? ShowDialog(string title, object datacontext)
    {
        var win = new WindowDialog();
        win.Title = title;
        win.DataContext = datacontext;

        return win.ShowDialog();
    }

}

WindowDialog is a special but simple window. I need it to hold my content:

<Window x:Class="WindowDialog"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    Title="WindowDialog" 
    WindowStyle="SingleBorderWindow" 
    WindowStartupLocation="CenterOwner" SizeToContent="WidthAndHeight">
    <ContentPresenter x:Name="DialogPresenter" Content="{Binding .}">

    </ContentPresenter>
</Window>

A problem with dialogs in wpf is the dialogresult = true. This can only be achieved in code. That's why I created an interface for my dialogviewmodel to implement.

public class RequestCloseDialogEventArgs : EventArgs
{
    public RequestCloseDialogEventArgs(bool dialogresult)
    {
        this.DialogResult = dialogresult;
    }

    public bool DialogResult
    {
        get; set;
    }
}

public interface IDialogResultVMHelper
{
    event EventHandler<RequestCloseDialogEventArgs> RequestCloseDialog;
}

Whenever my viewmodel think its time for dialogresult=true, then raise this event.

public partial class DialogWindow : Window
{
    //Merken wenn Window geschlossen wurde, damit kein DialogResult mehr gesetzt wird
    private bool _isClosed = false;

    public DialogWindow()
    {
        InitializeComponent();
        this.DialogPresenter.DataContextChanged += DialogPresenterDataContextChanged;
        this.Closed += DialogWindowClosed;
    }

    void DialogWindowClosed(object sender, EventArgs e)
    {
        this._isClosed = true;
    }

    private void DialogPresenterDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        var d = e.NewValue as IDialogResultVMHelper;

        if (d == null)
            return;

        d.RequestCloseDialog += new EventHandler<RequestCloseDialogEventArgs>(DialogResultTrueEvent).MakeWeak(eh => d.RequestCloseDialog -= eh); ;
    }

    private void DialogResultTrueEvent(object sender, RequestCloseDialogEventArgs eventargs)
    {
        //Wichtig damit für ein geschlossenes Window kein DialogResult mehr gesetzt wird
        //GC räumt Window irgendwann weg und durch MakeWeak fliegt es auch beim IDialogResultVMHelper raus
        if(_isClosed) return;

        this.DialogResult = eventargs.DialogResult;
    }

Now at least I have to create a DataTemplate in my resource file(app.xaml or something):

<DataTemplate DataType="{x:Type DialogViewModel:EditOrNewAuswahlItemVM}" >
        <DialogView:EditOrNewAuswahlItem/>
</DataTemplate>

Well thats all, I can now call dialogs from my viewmodels:

 var result = this.uiDialogService.ShowDialog("Dialogwindow title goes here", dialogwindowVM);

Now my question, do you see any problems with this solution?

Edit: for completeness. the viewmodel should implement IDialogResultVMHelper and then can raise it within a OkCommand or something like this

public class MyViewmodel : IDialogResultVMHelper
{
    private readonly Lazy<DelegateCommand> _okCommand;

    public MyViewmodel()
    {
         this._okCommand = new Lazy<DelegateCommand>(() => new DelegateCommand(() => InvokeRequestCloseDialog(new RequestCloseDialogEventArgs(true)), () => YourConditionsGoesHere = true));
    }

    public ICommand OkCommand
    { 
        get { return this._okCommand.Value; } 
    }

    public event EventHandler<RequestCloseDialogEventArgs> RequestCloseDialog;

    private void InvokeRequestCloseDialog(RequestCloseDialogEventArgs e)
    {
        var handler = RequestCloseDialog;
        if (handler != null) 
            handler(this, e);
    }
 }

EDIT 2: i use the code from http://diditwith.net/2007/03/23/SolvingTheProblemWithEventsWeakEventHandlers.aspx for making my Eventhandler register weak.

public delegate void UnregisterCallback<TE>(EventHandler<TE> eventHandler) 
    where TE : EventArgs;

public interface IWeakEventHandler<TE> 
    where TE : EventArgs
{
    EventHandler<TE> Handler { get; }
}

public class WeakEventHandler<T, TE> : IWeakEventHandler<TE> 
    where T : class 
    where TE : EventArgs
{
    private delegate void OpenEventHandler(T @this, object sender, TE e);

    private readonly WeakReference mTargetRef;
    private readonly OpenEventHandler mOpenHandler;
    private readonly EventHandler<TE> mHandler;
    private UnregisterCallback<TE> mUnregister;

    public WeakEventHandler(EventHandler<TE> eventHandler, UnregisterCallback<TE> unregister)
    {
        mTargetRef = new WeakReference(eventHandler.Target);

        mOpenHandler = (OpenEventHandler)Delegate.CreateDelegate(typeof(OpenEventHandler),null, eventHandler.Method);

        mHandler = Invoke;
        mUnregister = unregister;
    }

    public void Invoke(object sender, TE e)
    {
        T target = (T)mTargetRef.Target;

        if (target != null)
            mOpenHandler.Invoke(target, sender, e);
        else if (mUnregister != null)
        {
            mUnregister(mHandler);
            mUnregister = null;
        }
    }

    public EventHandler<TE> Handler
    {
        get { return mHandler; }
    }

    public static implicit operator EventHandler<TE>(WeakEventHandler<T, TE> weh)
    {
        return weh.mHandler;
    }
}

public static class EventHandlerUtils
{
    public static EventHandler<TE> MakeWeak<TE>(this EventHandler<TE> eventHandler, UnregisterCallback<TE> unregister)
      where TE : EventArgs
    {
        if (eventHandler == null)
            throw new ArgumentNullException("eventHandler");

        if (eventHandler.Method.IsStatic || eventHandler.Target == null)
            throw new ArgumentException("Only instance methods are supported.", "eventHandler");

        var wehType = typeof(WeakEventHandler<,>).MakeGenericType(eventHandler.Method.DeclaringType, typeof(TE));

        var wehConstructor = wehType.GetConstructor(new Type[] { typeof(EventHandler<TE>), typeof(UnregisterCallback<TE>) });

        IWeakEventHandler<TE> weh = (IWeakEventHandler<TE>)wehConstructor.Invoke(new object[] { eventHandler, unregister });

        return weh.Handler;
    }
}

Source: (StackOverflow)

Binding WPF ComboBox to a Custom List

I have a ComboBox that doesn't seem to update the SelectedItem/SelectedValue.

The ComboBox ItemsSource is bound to a property on a ViewModel class that lists a bunch of RAS phonebook entries as a CollectionView, then I've bound (at separate times) both the SelectedItem or SelectedValue to another property of the ViewModel. I have added a MessageBox into the save command to debug the values set by the databinding, but the SelectedItem/SelectedValue binding is not being set.

The ViewModel class looks something like this:

public ConnectionViewModel
{
    private readonly CollectionView _phonebookEntries;
    private string _phonebookeEntry;

    public CollectionView PhonebookEntries
    {
        get { return _phonebookEntries; }
    }

    public string PhonebookEntry
    {
        get { return _phonebookEntry; }
        set
        {
            if (_phonebookEntry == value) return;
            _phonebookEntry = value;
            OnPropertyChanged("PhonebookEntry");
        }
    }
}

The _phonebookEntries collection is being initialised in the constructor from a business object. The ComboBox XAML looks something like this:

<ComboBox ItemsSource="{Binding Path=PhonebookEntries}" 
    DisplayMemberPath="Name" 
    SelectedValuePath="Name" 
    SelectedValue="{Binding Path=PhonebookEntry}" />

I am only interested in the actual string value displayed in the ComboBox, not any other properties of the object as this is the value I need to pass across to RAS when I want to make the VPN connection, hence DisplayMemberPath and SelectedValuePath are both the Name property of the ConnectionViewModel. The ComboBox is in a DataTemplate applied to an ItemsControl on a Window who's DataContext has been set to a ViewModel instance.

The ComboBox displays the list of items correctly, and I can select one in the UI with no problem. However when I display the message box from the command, the PhonebookEntry property still has the initial value in it, not the selected value from the ComboBox. Other TextBox instances are updating fine and displaying in the MessageBox.

What am I missing with databinding the ComboBox? I've done a lot of searching and can't seem to find anything that I'm doing wrong.


This is the behaviour I'm seeing, however it's not working for some reason in my particular context.

I have a MainWindowViewModel which has a CollectionView of ConnectionViewModels. In the MainWindowView.xaml file code-behind, I set the DataContext to the MainWindowViewModel. The MainWindowView.xaml has an ItemsControl bound to the collection of ConnectionViewModels. I have a DataTemplate that holds the ComboBox as well as some other TextBoxes. The TextBoxes are bound directly to properties of the ConnectionViewModel using Text="{Binding Path=ConnectionName}".

public class ConnectionViewModel : ViewModelBase
{
    public string Name { get; set; }
    public string Password { get; set; }
}

public class MainWindowViewModel : ViewModelBase
{
    // List<ConnectionViewModel>...
    public CollectionView Connections { get; set; }
}

The XAML code-behind:

public partial class Window1
{
    public Window1()
    {
        InitializeComponent();
        DataContext = new MainWindowViewModel();
    }
}

Then XAML:

<DataTemplate x:Key="listTemplate">
    <Grid>
        <ComboBox ItemsSource="{Binding Path=PhonebookEntries}" 
            DisplayMemberPath="Name" 
            SelectedValuePath="Name" 
            SelectedValue="{Binding Path=PhonebookEntry}" />
        <TextBox Text="{Binding Path=Password}" />
    </Grid>
</DataTemplate>

<ItemsControl ItemsSource="{Binding Path=Connections}" 
    ItemTemplate="{StaticResource listTemplate}" />

The TextBoxes all bind correctly, and data moves between them and the ViewModel with no trouble. It's only the ComboBox that isn't working.

You are correct in your assumption regarding the PhonebookEntry class.

The assumption I am making is that the DataContext used by my DataTemplate is automatically set through the binding hierarchy, so that I don't have to explicitly set it for each item in the ItemsControl. That would seem a bit silly to me.


Here is a test implementation that demonstrates the problem, based on the example above.

XAML:

<Window x:Class="WpfApplication7.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <DataTemplate x:Key="itemTemplate">
            <StackPanel Orientation="Horizontal">
                <TextBox Text="{Binding Path=Name}" Width="50" />
                <ComboBox ItemsSource="{Binding Path=PhonebookEntries}" 
                    DisplayMemberPath="Name" 
                    SelectedValuePath="Name" 
                    SelectedValue="{Binding Path=PhonebookEntry}"
                    Width="200"/>
            </StackPanel>
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <ItemsControl ItemsSource="{Binding Path=Connections}" 
            ItemTemplate="{StaticResource itemTemplate}" />
    </Grid>
</Window>

The code-behind:

namespace WpfApplication7
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            DataContext = new MainWindowViewModel();
        }
    }

    public class PhoneBookEntry
    {
        public string Name { get; set; }
        public PhoneBookEntry(string name)
        {
            Name = name;
        }
    }

    public class ConnectionViewModel : INotifyPropertyChanged
    {

        private string _name;

        public ConnectionViewModel(string name)
        {
            _name = name;
            IList<PhoneBookEntry> list = new List<PhoneBookEntry>
                                             {
                                                 new PhoneBookEntry("test"),
                                                 new PhoneBookEntry("test2")
                                             };
            _phonebookEntries = new CollectionView(list);
        }
        private readonly CollectionView _phonebookEntries;
        private string _phonebookEntry;

        public CollectionView PhonebookEntries
        {
            get { return _phonebookEntries; }
        }

        public string PhonebookEntry
        {
            get { return _phonebookEntry; }
            set
            {
                if (_phonebookEntry == value) return;
                _phonebookEntry = value;
                OnPropertyChanged("PhonebookEntry");
            }
        }

        public string Name
        { 
            get { return _name; }
            set
            {
                if (_name == value) return;
                _name = value;
                OnPropertyChanged("Name");
            }
        }
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }

    public class MainWindowViewModel
    {
        private readonly CollectionView _connections;

        public MainWindowViewModel()
        {
            IList<ConnectionViewModel> connections = new List<ConnectionViewModel>
                                                          {
                                                              new ConnectionViewModel("First"),
                                                              new ConnectionViewModel("Second"),
                                                              new ConnectionViewModel("Third")
                                                          };
            _connections = new CollectionView(connections);
        }

        public CollectionView Connections
        {
            get { return _connections; }
        }
    }
}

If you run that example, you will get the behaviour I'm talking about. The TextBox updates its binding fine when you edit it, but the ComboBox does not. Very confusing seeing as really the only thing I've done is introduce a parent ViewModel.

I am currently labouring under the impression that an item bound to the child of a DataContext has that child as it's DataContext. I can't find any documentation that clears this up one way or the other.

I.e,

Window -> DataContext = MainWindowViewModel
..Items -> Bound to DataContext.PhonebookEntries
....Item -> DataContext = PhonebookEntry (implicitly associated)

I don't know if that explains my assumption any better?


To confirm my assumption, change the binding of the TextBox to be

<TextBox Text="{Binding Mode=OneWay}" Width="50" />

And this will show the TextBox binding root (which I'm comparing to the DataContext) is the ConnectionViewModel instance.


Source: (StackOverflow)

Data binding to SelectedItem in a WPF Treeview

How can I retrieve the item that is selected in a WPF-treeview? I want to do this in XAML, because I want to bind it.

You might think that it is SelectedItem but apparently that does not exist is readonly and therefore unusable.

This is what I want to do:

<TreeView ItemsSource="{Binding Path=Model.Clusters}" 
    		ItemTemplate="{StaticResource ClusterTemplate}"
    		SelectedItem="{Binding Path=Model.SelectedCluster}" />

I want to bind the SelectedItem to a property on my Model.

But this gives me the error:

'SelectedItem' property is read-only and cannot be set from markup.

Edit: Ok, this is the way that I solved this:

<TreeView
    	  ItemsSource="{Binding Path=Model.Clusters}" 
    	  ItemTemplate="{StaticResource HoofdCLusterTemplate}"
    	  SelectedItemChanged="TreeView_OnSelectedItemChanged" />

and in the codebehindfile of my xaml:

private void TreeView_OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
    Model.SelectedCluster = (Cluster)e.NewValue;
}

Source: (StackOverflow)

Handling Dialogs in WPF with MVVM

In the MVVM pattern for WPF, handling dialogs is one of the more complex operations. As your view model does not know anything about the view, dialog communication can be interesting. I can expose an ICommand that when the view invokes it, a dialog can appear.

Does anyone know of a good way to handle results from dialogs? I am speaking about windows dialogs such as MessageBox.

One of the ways we did this was have an event on the viewmodel that the view would subscribe to when a dialog was required.

public event EventHandler<MyDeleteArgs> RequiresDeleteDialog;

This is OK, but it means that the view requires code which is something I would like to stay away from.


Source: (StackOverflow)

MVVM Light Toolkit samples [closed]

Does anyone know opensource WPF applications created using MVVM Light Toolkit? Or any samples?


Source: (StackOverflow)

What is the difference between MVC and MVVM? [closed]

Is there a difference between the standard "Model View Controller" pattern and Microsoft's Model/View/ViewModel pattern?


Source: (StackOverflow)

MVVM Madness: Commands

I like MVVM. I don't love it, but like it. Most of it makes sense. But, I keep reading articles that encourage you to write a lot of code so that you can write XAML and don't have to write any code in the code-behind.

Let me give you an example.

Recently I wanted to hookup a command in my ViewModel to a ListView MouseDoubleClickEvent. I wasn't quite sure how to do this. Fortunately, Google has answers for everything. I found the following articles:

While the solutions were helpful in my understanding of commands, there were problems. Some of the aforementioned solutions rendered the WPF designer unusable because of a common hack of appending "Internal" after a dependency property; the WPF designer can't find it, but the CLR can. Some of the solutions didn't allow multiple commands to the same control. Some of the solutions didn't allow parameters.

After experimenting for a few hours I just decided to do this:

private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e) {
    ListView lv = sender as ListView;
    MyViewModel vm = this.DataContext as MyViewModel;

    vm.DoSomethingCommand.Execute(lv.SelectedItem);
}

So, MVVM purists, please tell me what's wrong with this? I can still Unit test my command. This seems very practical, but seems to violate the guideline of "ZOMG... you have code in your code-behind!!!!" Please share your thoughts.

Thanks in advance.


Source: (StackOverflow)

What is the best way to hide the screen while knockout js bindings are being built?

I'm a huge knockoutjs fan. I use it for all my web development now and simply love it. One thing that I've not been able to figure out though is how to hide the UI while the knockoutjs bindings are being built.

For example, I have a very robust user interface with lots of templates being used on my page. The problem that I'm noticing is that when the user first visits the page, they see all of my templates for a split second before the bindings kick in and hide them.

What is the best way to fix this problem? I've tried using helper classes to hide them, but then the templates are not able to be displayed using 'visible' and 'if' bindings unless I remove the helper class reference (ie. ui-helper-hidden).


Source: (StackOverflow)

What is Prism for WPF?

I've come across something called Prism a lot recently. Microsoft, who run the project, describe it as "guidelines for composite applications in WPF and Silverlight". Even after reading the more detailed descriptions out there, I have next to no clue what it's actually about, I'm afraid.

I'm hoping here that someone could give me a clear succinct explanation of what Prism actually is and why I should learn it. I have been a WPF developer for a couple of years now, used MVVM my fair share, and have lately encountered people using Prism, but personally feel a bit out of the loop here.

In particular, I'm wondering about the following points:

  • Is Prism literally just (or mainly) a booklet, as given on the MSDN site? Does it include any libraries, if so for what exactly?

  • Is Prism an MVVM framework? Should I be using it as the "official Microsoft MVVM framework" over others out there or my own?

  • Does it provide dependency injection? Does it relate to MEF at all in this way?

  • Anything else I should know about what Prism does, as a WPF/Silverlight developer.


Source: (StackOverflow)

WPF OpenFileDialog with the MVVM pattern?

I just started learning the MVVM pattern for WPF. I hit a wall: what do you do when you need to show an OpenFileDialog?

Here's an example UI I'm trying to use it on:

alt text

When the browse button is clicked, an OpenFileDialog should be shown. When the user selects a file from the OpenFileDialog, the file path should be displayed in the textbox.

How can I do this with MVVM?

Update: How can I do this with MVVM and make it unit test-able? The solution below doesn't work for unit testing.


Source: (StackOverflow)