使用WPF和MVVM设置数据绑定的问题

本文关键字:数据绑定 问题 设置 MVVM WPF 使用 | 更新日期: 2023-09-27 18:02:00

我有一个使用MVVM的应用程序。我试图通过连接到我的ViewModel中的属性来设置我的ComboBox的数据绑定。当我运行应用程序时,我得到这个错误消息:

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

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

使用WPF和MVVM设置数据绑定的问题

您没有正确绑定SelectedItem。绑定时需要设置Path,不能设置Source。我假设您已经将数据上下文设置为MainViewModel。因为LocationPicked属性是在MainViewModel中,你不需要设置Binding.Source

使用{Binding LocationPicked更改绑定以设置SelectedItem的路径。