[英]Problems setting up databinding with WPF and MVVM
我有一個使用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");
}
}
}
}
我是否錯誤地設置了屬性以使其與數據綁定一起使用?
您沒有正確綁定SelectedItem
。 您需要在綁定上設置Path
而不是Source
。 我假設您已將datacontext設置為MainViewModel。 由於LocationPicked
屬性位於MainViewModel中,因此您無需設置Binding.Source
。 使用{Binding LocationPicked
更改綁定以在SelectedItem上設置Path。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.