1

I have an application that uses MVVM. I'm trying to set up the databinding for my ComboBox by connecting it to the Properties in my ViewModel. When I run the application I get this error message:

Message='Provide value on 'System.Windows.Data.Binding' threw an exception.' Line number '11' and line position '176'.

The problem occurs with this line of XAML:

<ComboBox x:Name="schoolComboBox" HorizontalAlignment="Left" Margin="25,80,0,0" VerticalAlignment="Top" Width="250" FontSize="16" ItemsSource="{Binding LocationList}" SelectedItem="{Binding Source=LocationPicked}" />

Below is the ViewModel that I'm trying to use.

using QMAC.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Windows;

namespace QMAC.ViewModels
{
  class MainViewModel : ViewModelBase
  {
    Address address;
    Location location;
    private string _locationPicked;

    public MainViewModel()
    {
        address = new Address();
        location = new Location();
    }

    public List<string> LocationList
    {
        get { return location.site; }
        set
        {
            OnPropertyChanged("LocationList");
        }
    }

    public string LocationPicked
    {
        get { return _locationPicked; }
        set
        {
            _locationPicked = value;
            MessageBox.Show(_locationPicked);
            OnPropertyChanged("LocationPicked");
        }
    }
  }
}

Am I setting up the property incorrectly for it to work with the databinding?

Pallas
  • 1,499
  • 5
  • 25
  • 57

1 Answers1

3

You are not binding the SelectedItem correctly. You need to set the Path on the binding and not the Source. I'm assuming that you have set the datacontext to the MainViewModel. Since the LocationPicked property is in the MainViewModel you don't need to set the Binding.Source. Change your binding to set the Path on the SelectedItem using {Binding LocationPicked.

evanb
  • 3,061
  • 20
  • 32
  • That worked! So let me get this straight. The only time you have to use source is if you don't set the DataContext? If you have set the DataContext then you just say {Binding PropertyName} right? – Pallas Mar 01 '13 at 21:28
  • Right. The Binding.Source inherits the DataContext of the parent control, and that control inherits the DataContext of its parent control, and so on. If you want to set the source to something other than that, they you would explicitly set the source in the binding. – evanb Mar 01 '13 at 21:32
  • Alright last question, I have a CheckBox that I'm also trying to set up the databinding. For the ComboBox it was SelectedItem. What would be the equivalent for a CheckBox? – Pallas Mar 01 '13 at 21:36
  • Rachel explains the DataContext in her answer to this [SO post](http://stackoverflow.com/q/7262137/477530). As for your other question, you want to use the CheckBox.IsSelected property. – evanb Mar 01 '13 at 21:38
  • Glad my experience with WPF could help you. – evanb Mar 01 '13 at 21:48