如何为资源字典添加绑定? [英] How Can I Add a Binding to a Resource Dictionary?
问题描述
我的 UserControl
上有几个控件使用相同的可见性绑定:
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>
我试图将绑定添加到 UserControl.Resources
字典中:
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:
不能在类型的值"属性上设置绑定"字典条目".只能在DependencyObject的DependencyProperty`
A 'Binding' cannot be set on the 'Value' property of type 'DictionaryEntry'. A 'Binding' Can only be set on a DependencyProperty of a DependencyObject`
...但是后来我想到也许我应该在资源字典中放置一个 Visibility
值...但是我也无法使它正常工作.
... 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?
推荐答案
您不能.但是您可能想使用动态资源.像这样在App.xaml中创建可见性资源:
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>
要在XAML的任何位置绑定到此可见性,
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.
这篇关于如何为资源字典添加绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!