使用WPF和MVVM设置数据绑定的问题
问题描述:
我有一个使用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");
}
}
}
}
我是否正确设置属性以使其与数据绑定一起使用?
答
您没有正确地绑定SelectedItem
。您需要在绑定上设置Path
,而不是Source
。我假设你已经将datacontext设置为MainViewModel。由于LocationPicked
属性位于MainViewModel中,因此不需要设置Binding.Source
。使用{Binding LocationPicked
更改绑定以在SelectedItem上设置路径。
工作正常!所以让我弄清楚这一点。唯一一次你必须使用源代码是,如果你没有设置DataContext?如果你已经设置了DataContext,那么你只是说{Binding PropertyName}是正确的? – tylerbhughes 2013-03-01 21:28:45
没错。 Binding.Source继承父控件的DataContext,并且该控件继承其父控件的DataContext,依此类推。如果您想将源设置为除此之外的其他源,则可以在绑定中明确设置源。 – evanb 2013-03-01 21:32:42
好的最后一个问题,我有一个CheckBox,我也试图设置数据绑定。对于组合框它是SelectedItem。 CheckBox相当于什么? – tylerbhughes 2013-03-01 21:36:16