Reputation: 332
I have a simple binding question as I feel I'm missing something fundamental in my view of how binding works.
I assume that since I've set the DataContext of my MainWindow to a ViewModel in code-behind, that all of the binding in MainWindow.xaml would assume source of this DataContext unless otherwise specified. This does not seem to be the case when I'm using my UserControl (which itself has a ViewModel driving it)
My scenario is best described in code:
MainWindow.xaml.cs
private ViewModels.MainMenuViewModel vm;
public MainWindow()
{
InitializeComponent();
vm = new ViewModels.MainMenuViewModel();
this.DataContext = vm;
}
MainWindow.xaml (using the data-context set in code-behind)
x:Class="Mediafour.Machine.EditorWPF.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:uc="clr-namespace:Machine.EditorWPF.Views"
xmlns:local="clr-namespace:Machine.EditorWPF"
xmlns:localVM="clr-namespace:Machine.EditorWPF.ViewModels"
Title="MainWindow" Height="350" Width="650">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<uc:MachineTreeView x:Name="MachineTreeView" Grid.Column="0" MachineDocument="{Binding Path=CurrentDocument}" />
MainWindowViewModel.cs
public class MainWindowViewModel : ObservableObject
{
public MainWindowViewModel()
{
OpenMachine(@"D:\Projects\Agnes\EditorWPF\Test.machine");
}
private void OpenMachine(string filePath)
{
MachineDocument currentDocument = MachineDocument.OpenFile(filePath);
CurrentDocument = currentDocument;
}
private MachineDocument _currentDocument;
public MachineDocument CurrentDocument
{
get { return _currentDocument; }
set
{
if (_currentDocument != null)
{
_currentDocument.Dispose();
_currentDocument = null;
}
_currentDocument = value;
base.RaisePropertyChanged("CurrentDocument"); //this fires
}
}
Using this approach, the binding statement in MainWindow.xaml errors out. Looking at Snoop binding error, it states that the CurrentDocument property is not found in MachineViewModel
System.Windows.Data Error: 40 : BindingExpression path error: 'CurrentDocument' property not found on 'object' ''MachineViewModel' (HashCode=27598891)'. BindingExpression:Path=CurrentDocument; DataItem='MachineViewModel' (HashCode=27598891); target element is 'MachineTreeView' (Name='MachineTreeView'); target property is 'MachineDocument' (type 'MachineDocument')
Why is it looking at the MachineViewModel when the binding is done in MainWindow?
Other binding properties in MainWindow do work as expected, this is the only UserControl binding I have though.
Upvotes: 0
Views: 1179
Reputation: 17083
Either it is a simple mistake
MainMenuViewModel
instead of MainWindowViewModel
as MainWindow.DataContext
or maybe
DataContext
for the UserControl in the wrong manner. Take a look at this Simple Pattern for Creating Re-useable UserControls to do it the right way.Upvotes: 2