2013-03-01 68 views
1

我有一個使用MVVM的應用程序。我試圖通過將它連接到我的ViewModel中的屬性來設置我的ComboBox的數據綁定。當我運行應用程序,我收到此錯誤信息:這條線XAML的發生使用WPF和MVVM設置數據綁定的問題

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

問題:

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

下面是我試圖使用視圖模型。

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"); 
     } 
    } 
    } 
} 

我是否正確設置屬性以使其與數據綁定一起使用?

回答

3

您沒有正確地綁定SelectedItem。您需要在綁定上設置Path,而不是Source。我假設你已經將datacontext設置爲MainViewModel。由於LocationPicked屬性位於MainViewModel中,因此不需要設置Binding.Source。使用{Binding LocationPicked更改綁定以在SelectedItem上設置路徑。

+0

工作正常!所以讓我弄清楚這一點。唯一一次你必須使用源代碼是,如果你沒有設置DataContext?如果你已經設置了DataContext,那麼你只是說{Binding PropertyName}是正確的? – tylerbhughes 2013-03-01 21:28:45

+0

沒錯。 Binding.Source繼承父控件的DataContext,並且該控件繼承其父控件的DataContext,依此類推。如果您想將源設置爲除此之外的其他源,則可以在綁定中明確設置源。 – evanb 2013-03-01 21:32:42

+0

好的最後一個問題,我有一個CheckBox,我也試圖設置數據綁定。對於組合框它是SelectedItem。 CheckBox相當於什麼? – tylerbhughes 2013-03-01 21:36:16