【问题标题】:Problems setting up databinding with WPF and MVVM使用 WPF 和 MVVM 设置数据绑定的问题
【发布时间】:2013-02-16 12:06:08
【问题描述】:

我有一个使用 MVVM 的应用程序。我正在尝试通过将 ComboBox 连接到我的 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");
        }
    }
  }
}

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

【问题讨论】:

    标签: c# wpf data-binding mvvm viewmodel


    【解决方案1】:

    您没有正确绑定SelectedItem。您需要在绑定上设置Path 而不是Source。我假设您已将数据上下文设置为 MainViewModel。由于LocationPicked 属性位于MainViewModel 中,因此您无需设置Binding.Source。更改绑定以使用 {Binding LocationPicked 在 SelectedItem 上设置路径。

    【讨论】:

    • 成功了!所以让我直截了当。唯一必须使用 source 的情况是,如果您不设置 DataContext?如果您设置了 DataContext,那么您只需说 {Binding PropertyName} 对吗?
    • 对。 Binding.Source 继承父控件的 DataContext,该控件继承其父控件的 DataContext,依此类推。如果您想将源设置为其他内容,您可以在绑定中显式设置源。
    • 最后一个问题,我有一个复选框,我也在尝试设置数据绑定。对于 ComboBox,它是 SelectedItem。 CheckBox 的等价物是什么?
    • Rachel 在她对SO post 的回答中解释了 DataContext。至于您的其他问题,您想使用 CheckBox.IsSelected 属性。
    • 很高兴我的 WPF 经验可以帮助到你。
    猜你喜欢
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-19
    相关资源
    最近更新 更多