wpf - 如何解决 WPF 中的 "Binding Expression Path error"?

标签 wpf mvvm binding properties

我将模型对象的可观察集合绑定(bind)到数据网格。但是,当我将绑定(bind)设置为集合时,我收到了一个指向人员的路径错误。

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

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

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

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绑定(bind)路径和源设置如下:
                   <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 包含一个 CustomerModel 类型的 Observable 集合,称为 Customers。这就是我将 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 中的字段,所以不确定为什么在绑定(bind)期间找不到属性:
   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;

        }

    }          

最佳答案

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

它们表明您在名称中的某处有 3 个文本框 fNameTbx , lNameTbx , 和 emailTbx . DataGrid 不会生成具有 Name 属性的项目,因此它不是导致这些绑定(bind)错误的原因。

尝试读取绑定(bind)错误时,最好用分号将它们分开并向后读取,如 here 所示。 .

例如,

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'(名称='fNameTbx');
  • DataItem='MainViewModel' (HashCode=55615518);
  • BindingExpression 路径错误:在“对象”“MainViewModel”(HashCode=55615518)上找不到“FirstName”属性。绑定(bind)表达式:路径=名字;

  • 意思是你有的地方
    <TextBox Name="fNameTbx" Text="{Binding FirstName}" />
    
    DataContext此 TextBox 的类型为 MainViewModel .和MainViewModel没有 FirstName 的属性.

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

    关于wpf - 如何解决 WPF 中的 "Binding Expression Path error"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33805067/

    相关文章:

    c# - 基于不同XAML的样式继承

    wpf - 我什么时候应该使用 FrameworkPropertyMetadata 或 UIPropertyMetadata 而不是普通的 PropertyMetadata?

    MvvmCross:应用程序范围的 View 模型?

    mvvm - ViewModel 之间的通信

    cocoa - 验证 TextField 中的文本

    c# - 将 KeyVaultClient 与 MSAL token "Unauthorized"结合使用

    wpf - 在 PlacementTarget 的中心和底部对齐的弹出窗口

    javascript - Knockout.js 多个外部模板和多个 VM 切换失败

    wpf usercontrol,将按钮的命令参数绑定(bind)到父用户控件

    java - 如何将 TableView 内的 TableColumn 的总和绑定(bind)到外部 Label textProperty()?