I’m developing a WPF/PRISM based application. The parent view(usercontrol) has many regions in it and child views(usercontrol) are loaded in those regions. When the child views are getting loaded I can see binding errors printed in the console. Even though the bound properties are part of the child view’s viewmodel the binding resolution seems to first look at parent view’s view model and throws this error. The application works fine, I want to know if I can get rid of these errors.
I have managed to recreate this in a simple app that I wrote.
C#
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
this.Loaded += (o, e) => { this.layout.DataContext = new ViewModel(); };
}
}
public class ViewModel
{
public ViewModel()
{
this.SampleText = "Sample";
}
public string SampleText { get; set; }
}
XAML
<Window x:Class="DataBindingResolution.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:diagnostics="clr-namespace:System.Diagnostics;assembly=WindowsBase"
Title="MainWindow" Height="350" Width="525">
<Grid x:Name="layout">
<Grid.Resources>
<TextBlock x:Key="test" Text="{Binding SampleText}"/>
</Grid.Resources>
<Button Content="{StaticResource test}"/>
</Grid>
</Window>
When you run this sample you can see:
System.Windows.Data Error: 39 :
BindingExpression path error:
‘SampleText’ property not found on
‘object’ ”MainWindow’ (Name=”)’.
BindingExpression:Path=SampleText;
DataItem=’MainWindow’ (Name=”);
target element is ‘TextBlock’
(Name=”); target property is ‘Text’
(type ‘String’)
getting printed in the console even though the button correctly shows the text “Sample” in it. How do I get rid of this message from being printed in the console, my application prints 25+ errors for each child view loaded.
You should probably separate the two ViewModels into two classes. Then have the parent ViewModel reference the child ViewModel. Everything else can be accomplished through binding.
This simplified Xaml would like like: