How Can I Add a Binding to a Resource Dictionary?

僤鯓⒐⒋嵵緔 提交于 2019-12-14 03:24:26

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/37396964/how-can-i-add-a-binding-to-a-resource-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!