如何解决“绑定表达路径错误"?在WPF中? [英] How to resolve a "Binding Expression Path error" in WPF?

查看:75
本文介绍了如何解决“绑定表达路径错误"?在WPF中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将模型对象的可观察集合绑定到数据网格.但是,当我将集合设置为绑定时,会出现人为错误的路径.

I'm binding an observsable collection of model objects to a data grid. But when I set the binding to the collection, I get a path error to the peoprties.

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

In debugging this issue, I've checked that the public properties in the CustomerModel are correctly named in the DataGrid binding. And also that the collection being returned to the model isn't empty. I also checked that the data context is set correctly in the View's code behind.

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

I think it might be an error due to the way I've specified the binding path in the xaml..

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

The full details of the binding error is as follows, for each field:

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')

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

Could anyone point me in the right direction, in order to debug this further?

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

DataGrid binding path and source are set as follows:

                   <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>

视图模型包含一个名为CustomerModel的CustomerModel类型的Observable集合.这就是我将DataGrid ItemSource设置为的内容. (出于可读性考虑,我已从VM中删除了其他代码)

The View Model contains an Observable collection of type CustomerModel, called Customers. This is what I've set the DataGrid ItemSource to. (I've removed other code from VM for readability)

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中的字段,因此不确定在绑定过程中为什么找不到属性:

And these are the fields that in the CustomerModel, so not sure why the properties are not being found during binding:

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

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

This is how the data context is set in the View's code behind:

    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;

        }

    }          

推荐答案

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

These binding errors are not related to your DataGrid.

它们表示您在名称fNameTbxlNameTbxemailTbx的某处有3个文本框. DataGrid不会生成具有Name属性的项,因此它不是导致这些绑定错误的项.

They indicate that you have 3 TextBoxes somewhere of the names fNameTbx, lNameTbx, and emailTbx. A DataGrid does not generate it's items with a Name property, so it is not the one causing these binding errors.

尝试读取绑定错误时,最好按分号将它们分解并向后读取,如此处

When trying to read binding errors, it's best to break them up by semi-colons and read them backwards, as demonstrated here.

例如,

System.Windows.Data错误:40:BindingExpression路径错误:在对象""MainViewModel"(HashCode = 55615518)"上找不到"FirstName"属性. BindingExpression:Path = FirstName; DataItem ='MainViewModel'(HashCode = 55615518);目标元素是'TextBox'(Name ='fNameTbx');目标属性是文本"(类型为字符串")

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')

也可以读为

  • 目标属性为文本"(类型为字符串")
  • 目标元素是'TextBox'(Name ='fNameTbx');
  • DataItem ='MainViewModel'(HashCode = 55615518);
  • BindingExpression路径错误:在对象""MainViewModel"(HashCode = 55615518)"上找不到"FirstName"属性. BindingExpression:Path = FirstName;

意味着您拥有的地方

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

此文本框的DataContext的类型为MainViewModel.并且MainViewModel不具有FirstName的属性.

Where the DataContext of this TextBox is of type MainViewModel. And MainViewModel does not have a property of FirstName.

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

I'd recommend searching your project for those names, or you could use a tool like Snoop to debug databindings and DataContext issues at runtime.

这篇关于如何解决“绑定表达路径错误"?在WPF中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆