C# 使用WPF和MVVM设置数据绑定时出现问题

C# 使用WPF和MVVM设置数据绑定时出现问题,c#,wpf,data-binding,mvvm,viewmodel,C#,Wpf,Data Binding,Mvvm,Viewmodel,我有一个使用MVVM的应用程序。我正试图通过将组合框连接到ViewModel中的属性来设置组合框的数据绑定。运行应用程序时,我收到以下错误消息: Message='Provide value on 'System.Windows.Data.Binding' threw an exception.' Line number '11' and line position '176'. 这行XAML出现问题: <ComboBox x:Name="schoolComboBox" Horizont

我有一个使用MVVM的应用程序。我正试图通过将组合框连接到ViewModel中的属性来设置组合框的数据绑定。运行应用程序时,我收到以下错误消息:

Message='Provide value on 'System.Windows.Data.Binding' threw an exception.' Line number '11' and line position '176'.
这行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}" />

下面是我尝试使用的ViewModel

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");
        }
    }
  }
}
使用QMAC.Models;
使用制度;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Windows;
命名空间QMAC.ViewModels
{
类MainViewModel:ViewModelBase
{
地址;
位置;
私有字符串_locationPicked;
公共主视图模型()
{
地址=新地址();
位置=新位置();
}
公共列表位置列表
{
获取{return location.site;}
设置
{
OnPropertyChanged(“位置列表”);
}
}
已选择公共字符串位置
{
获取{return\u locationPicked;}
设置
{
_位置=值;
MessageBox.Show(_locationPicked);
OnPropertyChanged(“LocationPicked”);
}
}
}
}

我是否错误地设置了属性以使其与数据绑定一起工作?

您没有正确绑定
SelectedItem
。您需要在绑定上设置
路径
,而不是
。我假设您已将datacontext设置为MainViewModel。由于
LocationPicked
属性位于MainViewModel中,因此不需要设置
Binding.Source
。使用有效的
{binding LocationPicked

更改绑定以设置SelectedItem上的路径!让我直截了当地说吧。如果您没有设置DataContext,则只需使用source。如果您设置了DataContext,则只需说{binding PropertyName}对吗?对。Binding.Source继承父控件的DataContext,而该控件继承其父控件的DataContext,依此类推。如果您想将源设置为其他值,您应该在绑定中显式设置源。好的,最后一个问题,我有一个复选框,我也在尝试设置数据绑定。对于ComboBox,它是SelectedItem。复选框的等价物是什么?Rachel在回答这个问题时解释了DataContext。至于你的另一个问题,你想使用CheckBox.IsSelected属性。很高兴我的WPF经验能帮到你。