如何解决WPF中的“绑定表达式路径错误”?

时间:2015-11-19 13:18:37

标签: wpf mvvm binding properties

我将一个可观察的模型对象集合绑定到数据网格。但是当我将绑定设置为集合时,我得到了路径错误。

在调试此问题时,我检查了CustomerModel中的公共属性是否在DataGrid绑定中正确命名。而且返回到模型的集合也不是空的。我还检查了数据上下文是否在View后面的代码中正确设置。

我认为这可能是一个错误,因为我在xaml中指定了绑定路径的方式..

对于每个字段,绑定错误的完整详细信息如下:

System.Windows.Data Error: 40 : BindingExpression path error: 'FirstName' property not found on 'object' ''MainViewModel' (HashCode=55615518)'. BindingExpression:Path=FirstName; DataItem='MainViewModel' (HashCode=55615518); target element is 'TextBox' (Name='fNameTbx'); target property is 'Text' (type 'String')

System.Windows.Data Error: 40 : BindingExpression path error: 'LastName' property not found on 'object' ''MainViewModel' (HashCode=55615518)'. BindingExpression:Path=LastName; DataItem='MainViewModel' (HashCode=55615518); target element is 'TextBox' (Name='lNameTbx'); target property is 'Text' (type 'String')

System.Windows.Data Error: 40 : BindingExpression path error: 'Email' property not found on 'object' ''MainViewModel' (HashCode=55615518)'. BindingExpression:Path=Email; DataItem='MainViewModel' (HashCode=55615518); target element is 'TextBox' (Name='emailTbx'); target property is 'Text' (type 'String')

有人能指出我正确的方向,以便进一步调试吗?

DataGrid绑定路径和源设置如下:

                   <DataGrid Name="infogrid"
                              Grid.Row="0"
                              Grid.RowSpan="3"
                              Grid.Column="1"
                              Grid.ColumnSpan="3"
                              AutoGenerateColumns="False"
                              ItemsSource="{Binding Customers}"
                              SelectedItem="{Binding SelectedCustomer}">
                        <DataGrid.Columns>
                            <DataGridTextColumn Binding="{Binding Customers.Id}" Header="ID" />
                            <DataGridTextColumn Binding="{Binding Customers.FirstName}" Header="First Name" />
                            <DataGridTextColumn Binding="{Binding Customers.LastName}" Header="Last Name" />
                            <DataGridTextColumn Binding="{Binding Customers.Email}" Header="Email" />
                        </DataGrid.Columns>
                    </DataGrid>

View Model包含一个名为Customers的CustomerModel类型的Observable集合。这就是我将DataGrid ItemSource设置为的内容。 (为了便于阅读,我已从VM中删除了其他代码)

namespace MongoDBApp.ViewModels
{

    class MainViewModel : INotifyPropertyChanged
    {

        public event PropertyChangedEventHandler PropertyChanged = delegate { };
        private ICustomerDataService _customerDataService;


        public MainViewModel(ICustomerDataService customerDataService)
        {
            this._customerDataService = customerDataService;
            QueryDataFromPersistence();
        }



        private ObservableCollection<CustomerModel> customers;
        public ObservableCollection<CustomerModel> Customers
        {
            get
            {
                return customers;
            }
            set
            {
                customers = value;
                RaisePropertyChanged("Customers");
            }
        }



        private void QueryDataFromPersistence()
        {
            Customers = _customerDataService.GetAllCustomers().ToObservableCollection();

        }



        private void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }



    }
}

这些是CustomerModel中的字段,因此不确定为什么在绑定期间找不到属性:

   public class CustomerModel : INotifyPropertyChanged
    {

        private ObjectId id;
        private string firstName;
        private string lastName;
        private string email;


        [BsonElement]
        ObservableCollection<CustomerModel> customers { get; set; }

        /// <summary>
        /// This attribute is used to map the Id property to the ObjectId in the collection
        /// </summary>
        [BsonId]
        public ObjectId Id { get; set; }

        [BsonElement("firstName")]
        public string FirstName
        {
            get
            {
                return firstName;
            }
            set
            {
                firstName = value;
                RaisePropertyChanged("FirstName");
            }
        }

        [BsonElement("lastName")]
        public string LastName
        {
            get
            {
                return lastName;
            }
            set
            {
                lastName = value;
                RaisePropertyChanged("LastName");
            }
        }

        [BsonElement("email")]
        public string Email
        {
            get
            {
                return email;
            }
            set
            {
                email = value;
                RaisePropertyChanged("Email");
            }
        }


        public event PropertyChangedEventHandler PropertyChanged;
        private void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

这是在后面的View代码中设置数据上下文的方式:

    public partial class MainView : Window
    {
        private MainViewModel ViewModel { get; set; }
        private static ICustomerDataService customerDataService = new CustomerDataService(CustomerRepository.Instance);


        public MainView()
        {
            InitializeComponent();
            ViewModel = new MainViewModel(customerDataService);
            this.DataContext = ViewModel;

        }

    }          

4 个答案:

答案 0 :(得分:8)

这些绑定错误与您的DataGrid无关。

它们表示您在名称fNameTbxlNameTbxemailTbx的某处有3个TextBox。 DataGrid不会使用Name属性生成它的项目,因此它不是导致这些绑定错误的项目。

当试图读取绑定错误时,最好用分号将它们分解并向后读取它们,如here所示。

例如,

  

System.Windows.Data错误:40:BindingExpression路径错误:'object'''MainViewModel'(HashCode = 55615518)'上找不到'FirstName'属性。 BindingExpression:路径=姓; DataItem ='MainViewModel'(HashCode = 55615518); target元素是'TextBox'(Name ='fNameTbx'); target属性是'Text'(类型'String')

也可以读作

  • target属性为'Text'(类型'String')
  • 目标元素是'TextBox'(Name ='fNameTbx');
  • DataItem ='MainViewModel'(HashCode = 55615518);
  • BindingExpression路径错误:'object'''MainViewModel'(HashCode = 55615518)'上找不到'FirstName'属性。 BindingExpression:路径=姓;

意味着你有

<TextBox Name="fNameTbx" Text="{Binding FirstName}" />

此TextBox的DataContext类型为MainViewModelMainViewModel没有FirstName的属性。

我建议您在项目中搜索这些名称,或者可以使用Snoop之类的工具在运行时调试数据绑定和DataContext问题。

答案 1 :(得分:1)

异常表明DataBinding引擎正在FirstName上查找字段LastNameMainViewModel等,而不是CustomerModel

您无需在列的各个绑定表达式中指定属性Customers

<DataGrid.Columns>
  <DataGridTextColumn Binding="{Binding Id}" Header="ID" />
  <DataGridTextColumn Binding="{Binding FirstName}" Header="First Name" />
  <DataGridTextColumn Binding="{Binding LastName}" Header="Last Name" />
  <DataGridTextColumn Binding="{Binding Email}" Header="Email" />
</DataGrid.Columns>

答案 2 :(得分:0)

当我在DataTemplate中使用TextBlock文本绑定时,我遇到了同样的问题,最终不得不这样做:

[JsonIgnore]

使其正常工作。尝试添加“ DataContext”。在酒店前面,看看是否可行。

答案 3 :(得分:0)

public Window()
{
      this.DataContext = this;
      InitializeComponent();
}
public string Name {get;set;}
//xaml
<TextBlock Text="{Binding Name}"/>

this.DataContext = this;InitializeComponent();之前
(在InitializeComponent()中加载xaml之前需要DataContext可用)

属性Name应该是public{ get; }
(如果为私有,则wpf无法访问)