Search code examples
c#wpfxamlmvvmbinding-expressions

Strange BindingExpression path error with ContentPresenter


In my program I have a mainWindow that contains a contentPresenter. The mainWindow has a ViewModel called MainWindowViewModel. This viewModel contains properties that are bound to items in the mainWindow.

The Content of my contentPresenter is represented by a UserControl->ViewModel->Model structure.

This is the xaml of the contentPresenter that I am working with.

MainWindow.xaml:

<ContentPresenter Content="{Binding LeftWidget}" IsEnabled="{Binding LeftWidgetEnabled}" ... />

LeftWidget and LeftWidgetEnabled are both properties located in MainWindowViewModel. However, the BindingExpression path error that I receive has to do with LeftWidgetEnabled. For some reason my program is looking for the property in the ViewModel of the contentPresenter's UserControl. This doesn't make much sense to me, because the program deals with the LeftWidget property correctly.

Both properties are located in MainWindowViewModel, so why would the program be looking elsewhere for the LeftWidgetEnabled property? How can I fix this?

Also Note: The way that I set the DataContext of my UserControls are like so...

Under <Window.Resources... in mainWindow.xaml:

<DataTemplate DataType="{x:Type project:LeftWidgetViewModel}">
    <local:LeftWidgetUserControl/>
</DataTemplate>

Solution

  • chnage the binding path to (this assumes main window is in fact a window object):

    IsEnabled={Binding DataContext.LeftWidgetEnabled, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}
    

    does that help? If so then you need to examine the datacontext of your objects as there might be something else going on

    also, does the datatype of LeftWidgetEnabled match what is expected by the IsEnabled Property, ie boolean to boolean?