如何解决 WPF 中的“绑定表达式路径错误”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33805067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to resolve a "Binding Expression Path error" in WPF?
提问by Brian J
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.
我将一个可观察的模型对象集合绑定到数据网格。但是当我将绑定设置为集合时,我收到了一个指向 peoprties 的路径错误。
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.
在调试此问题时,我检查了 CustomerModel 中的公共属性是否在 DataGrid 绑定中正确命名。而且返回给模型的集合不是空的。我还检查了数据上下文在后面的视图代码中是否正确设置。
I think it might be an error due to the way I've specified the binding path in the xaml..
我认为这可能是由于我在 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 binding path and source are set as follows:
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>
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)
视图模型包含一个 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));
}
}
}
}
And these are the fields that in the CustomerModel, so not sure why the properties are not being found during binding:
这些是 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));
}
}
}
This is how the data context is set in the View's code behind:
这是在后面的 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;
}
}
回答by Rachel
These binding errors are not related to your DataGrid.
这些绑定错误与您的 DataGrid 无关。
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.
他们表明你有3个文本框的地方的名字fNameTbx,lNameTbx和emailTbx。DataGrid 不会生成具有 Name 属性的项目,因此它不是导致这些绑定错误的原因。
When trying to read binding errors, it's best to break them up by semi-colons and read them backwards, as demonstrated here.
当试图读取绑定错误,最好用分号来打破他们和向后阅读,这表现在这里。
For example,
例如,
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 错误:40:BindingExpression 路径错误:在“对象”“MainViewModel”(HashCode=55615518)上找不到“FirstName”属性。绑定表达式:路径=名字;DataItem='MainViewModel' (HashCode=55615518); 目标元素是 'TextBox' (Name='fNameTbx'); 目标属性是“文本”(类型“字符串”)
Can also be read as
也可以读作
- target property is 'Text' (type 'String')
- target element is 'TextBox' (Name='fNameTbx');
- DataItem='MainViewModel' (HashCode=55615518);
- BindingExpression path error: 'FirstName' property not found on 'object' ''MainViewModel' (HashCode=55615518)'. BindingExpression:Path=FirstName;
- 目标属性是“文本”(类型“字符串”)
- 目标元素是 'TextBox' (Name='fNameTbx');
- DataItem='MainViewModel' (HashCode=55615518);
- BindingExpression 路径错误:在“对象”“MainViewModel”(HashCode=55615518)上找不到“FirstName”属性。绑定表达式:路径=名字;
Meaning somewhere you have
意思是你有的地方
<TextBox Name="fNameTbx" Text="{Binding FirstName}" />
Where the DataContextof this TextBox is of type MainViewModel. And MainViewModeldoes not have a property of FirstName.
当DataContext这个文本框是类型MainViewModel。并且MainViewModel没有 的属性FirstName。
I'd recommend searching your project for those names, or you could use a tool like Snoopto debug databindings and DataContext issues at runtime.
我建议在您的项目中搜索这些名称,或者您可以使用Snoop 之类的工具在运行时调试数据绑定和 DataContext 问题。
回答by Ethan Cabiac
The exceptions indicate that the DataBinding engine is looking for the fields FirstName, LastName, etc. on MainViewModelas opposed to CustomerModel.
例外情况表明,数据绑定引擎寻找领域FirstName,LastName等上MainViewModel而不是CustomerModel。
You don't need to specify the property Customersin the individual binding expressions for the columns:
您不需要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>
回答by MattE
I was having the same issue when I had the TextBlock Text Binding inside of a DataTemplate and I ended up having to do:
当我在 DataTemplate 中使用 TextBlock 文本绑定时,我遇到了同样的问题,我最终不得不这样做:
Text={Binding DataContext.SuccessTxt}
to get it to work properly. Try adding "DataContext." in front of the property and see if that works.
使其正常工作。尝试添加“DataContext”。在物业前面,看看是否有效。
回答by Tr??ng Qu?c Khánh
public Window()
{
this.DataContext = this;
InitializeComponent();
}
public string Name {get;set;}
//xaml
<TextBlock Text="{Binding Name}"/>
this.DataContext = this;before InitializeComponent();
(DataContext need available before load xaml in InitializeComponent())
this.DataContext = this;之前InitializeComponent();
(DataContext 需要在加载 xaml 之前可用InitializeComponent())
Properties Nameshould be publicand { get; }
(If private then wpf can't access)
属性Name应该是public和{ get; }
(如果是私有的,则 wpf 无法访问)

