Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF MVVM - Custom Control won't bind to Visibility if I set the DataContext to the code behind

I wanted to do a quick user control for my app, but to keep things in a MVVM style I thought I'd set the DataContext of the XAML to the code behind in my UserControl.

i.e.

DataContext="{Binding RelativeSource={RelativeSource Self}}"

This allows me to bind the XAML to properties in my code behind.

Everything went well until I came to bind the Visibility of an instance of the control to a Visibility property on a ViewModel.

<Controls:RoundProgress Visibility="{Binding ProgressVisibility}" Width="100" Height="100"></Controls:RoundProgress>

The Visibility no longer works - if I remove my tinkerings with the DataContext from the User Control - the visibility works!

Can someone set me right please? Thanks

like image 250
Andy Clarke Avatar asked Dec 09 '22 14:12

Andy Clarke


1 Answers

Don't set the DataContext of the UserControl itself from the internal XAML. By doing that you override the inherited DataContext and make your Binding look for a ProgressVisibility property on the UC instead of your ViewModel. Instead set the DataContext on an element inside the UC:

<UserControl x:Class...>
  <Grid DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}">
    ...
  </Grid>
</UserControl>
like image 161
John Bowen Avatar answered Dec 29 '22 12:12

John Bowen