My code behind file has its corresponding View Model as a public property for one of my Windows. I tried to data bind my ViewModel with the UI Elements in XAML but I always get error messages for that. However, when I try to create data bind using code, it works without any issues. I am really confused as to why this is happening and would like some guidance on what I am doing wrong.
Scenario 1 - Data binding fails when done in xaml
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(...);
}
}
Error Messages in Output Window:
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')
Scenario 2 - Data binding works when done in code
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;
}
}
Edit (09/08/2013)
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(...);
}
}