我的代码隐藏文件将其对应的View Model作为我的一个Windows的公共属性。我尝试将我的ViewModel数据绑定到XAML中的UI元素,但我总是收到错误消息。但是,当我尝试使用代码创建数据绑定时,它可以正常工作。我真的很困惑为什么会这样,并希望得到一些关于我做错的指导。
ProductInfoWindow.xaml:
<Window ...>
<Grid Name="grdProd" DataContext="{Binding RelativeSource={RelativeSource Self}, Path=ViewModel}">
<TextBox Name="txtName" Text="{Binding Product.Name}" />
</Grid>
</Window>
ProductInfoWindow.xaml.cs:
public partial class ProductInfoWindow : Window
{
public ProductInfoViewModel ViewModel { get; set; }
public ProductInfo()
{
ViewModel = new ProductInfoViewModel(...);
}
}
输出窗口中的错误消息:
System.Windows.Data Error: 40 : BindingExpression path error: 'ViewModel' property not
found on 'object' ''Grid' (Name='grdProd')'. BindingExpression:Path=ViewModel;
DataItem='Grid' (Name='grdProd'); target element is 'Grid' (Name='grdProd'); target
property is 'DataContext' (type 'Object')
ProductInfoWindow.xaml:
<Window ...>
<Grid Name="grdProd">
<TextBox Name="txtName" Text="{Binding Product.Name}" />
</Grid>
</Window>
ProductInfoWindow.xaml.cs:
public partial class ProductInfoWindow : Window
{
public ProductInfoViewModel ViewModel { get; set; }
public ProductInfo()
{
ViewModel = new ProductInfoViewModel(...);
grdProd.DataContext = ViewModel;
}
}
ProductInfoViewModel.cs
public class ProductInfoViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
PropertyChanged(this, e);
}
private Product m_product;
public Product Product
{
get
{
return m_product;
}
set
{
m_product = value;
OnPropertyChanged(new PropertyChangedEventArgs("Product"));
}
}
public ProductInfoViewModel(...)
{
Product = new Product(...);
}
}
答案 0 :(得分:1)
您的错误消息告诉您,在ViewModel
Grid
上找不到'grdProd'
媒体资源,这是一个公平的点,因为您的Viewmodel
是在ProductInfoWindow
班级定义的公共财产。
尝试设置Datacontext
级Window
代替(适应您的示例):
<Window DataContext="{Binding RelativeSource={RelativeSource Self}, Path=ViewModel}" ...>
<Grid Name="grdProd">
<TextBox Name="txtName" Text="{Binding Product.Name}" />
</Grid>
</Window>