Scott Baker
Scott Baker

Reputation: 10443

How Can I Add a Binding to a Resource Dictionary?

I have several controls on my UserControl that use the same Visibility Binding:

<UserControl x:Class="Whatever.MyClass"
             x:Name ="TheUserControlName"
             DataContext="MyUserControlViewModel">

    <Label x:Name="MyLabel" 
           Visibility="{Binding SomeBoolean, 
               ConverterParameter={StaticResource BooleanToVisibilityConverter},
               Converter={StaticResource BooleanValueInverter}}"
       Style="{StaticResource LeftLabel}"
       Content="Template _Name"
       Target="{Binding ElementName=SomeTextBox}" />
</UserControl>

I tried to add the binding to the UserControl.Resources dictionary:

<Binding x:Key="IsCourseVisibilityBinding"
         Path="Thing.SomeBoolean"
         ConverterParameter="{StaticResource BooleanToVisibilityConverter}"
         Converter="{StaticResource BooleanValueInverter}" /> 

... and I get the error:

A 'Binding' cannot be set on the 'Value' property of type 'DictionaryEntry'. A 'Binding' Can only be set on a DependencyProperty of a DependencyObject`

... but then it occured to me that maybe I should be putting a Visibility value in the resource dictionary... but I can't get that to work either.

How can I refactor the Visibility Binding so that I only have to define it once?

Upvotes: 0

Views: 7503

Answers (1)

Matas
Matas

Reputation: 860

You can't. But you may want to use dynamic resources. Create visibility resource(s) inside App.xaml like this:

<Application.Resources>
   <ResourceDictionary
      <Visibility x:Key="SomeVisibility">Visible</Visibility>
   </ResourceDictionary>
</Application.Resources>

To bind to this visibility anywhere from XAML:

<Button Content="Some button" Visibility="{DynamicResource SomeVisibility}"/>

Now to change value of this resource you can call this anywhere from code:

 Application.Current.Resources["SomeVisibility"] = Visibility.Collapsed;

Edit: Actually you can define dynamic resources for specific user control if you don't want them to be global in all application.

Upvotes: 3

Related Questions