This project has moved and is read-only. For the latest updates, please go here.

Tracking SelectedItem

Jan 21, 2010 at 4:46 PM

In my ViewModel I am having to track the SelectedItem by binding to the ViewModel. Then I have to query the View for the ViewModel and ViewModel for the Model to track the corresponding selected Model item:

        private void MainViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
            if (e.PropertyName == "ActiveScenarioView")
                IView view = activeScenarioView as IView;
                if (view != null)
                    ScenarioViewModel scenarioViewModel = view.GetViewModel<ScenarioViewModel>();
                    if (scenarioViewModel != null)
                        activeScenario = scenarioViewModel.Scenario;

The problem is I am getting an exception at ViewExtensions.DoEvents(): Dispatcher.PushFrame(frame); ArgumentException with message "Width must be non-negative". I have not been able to find a work-around for this.

Is there a better way of tracking the selected or active model object rather than having to query the View from the ViewModel?


Jan 22, 2010 at 10:23 AM

The exception is due to a the dispatcher being cleared with a third-party control in an invalid state. The invalid state occurs because it expects a value for a certain property that happens to be databound in my app but the application layer/model is not fully initialised and no value is bound before the message pump is cleared.

I am working with the control vendor to see if they can alleviate this issue but I need a work around for the time being.

I decided to go with data templating:

<DataTemplate DataType="{x:Type vm:ScenarioViewModel}">
    <view:ScenarioView />

So I can maintain a reference directly to the ViewModel and there is no need to call view.GetViewModel<T>();


  1. The above approach is common amongst other MVVM frameworks - why did WAF not choose this route?
  2. I suspect there are issues combining the two approaches. Can you see any issues with this?
Jan 25, 2010 at 9:00 PM

Hello Skina,

Thanks for your feedback. A workaround for the issue from your first post might be:

ScenarioViewModel scenarioViewModel = view.DataContext as ScenarioViewModel;

The variable scenarioViewModel might be null when the dispatcher didn’t run first.

1. Why does WAF not use data templating by default:

I started with data templating in my first approach to use the MVVM pattern but run immediately into a few limitations. That’s the reason I have changed the strategy.

2. You can use data templating with WAF.

In this case I would inherit my ViewModel from the Model class instead of the ViewModel base class.

Best Regards,