将 ResourceDictionary 中的样式绑定到用户控件

Binding styles from ResourceDictionary to usercontrols

我是 wpf 的新手,所以我正在寻找解决方案并解释为什么我尝试的解决方案不起作用。

这是我的案例。 我有几个用户控件。在他们每个人中,我都应用以下样式:

<UserControl.Resources>
    <Style TargetType="TextBox" BasedOn="{StaticResource Centratura}">
        <Setter Property="IsEnabled" Value="{Binding Property1.IsAbilitato}" />
    </Style>
</UserControl.Resources>

基于资源字典中定义的样式。 而且效果很好。 但请注意,对于每个 UserControl,前面的代码是相同的,除了绑定 属性,它将是 Property1.IsAbilitato、Property2.IsAbilitato、Property3.IsAbilitato...

但这是我不喜欢的代码重复。我想知道如何将样式放入资源字典并稍后在每个用户控件中应用正确的绑定。

我尝试按照建议 here 使用标签 属性,这样:

在我的用户控件中:

<UserControl x:Class="whatever"
    ...
    Tag="{Binding Property1.IsAbilitato}"
    ...>

并在资源词典中:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="TextBox">
        <Setter Property="IsEnabled" Value="{Binding Path=Tag, RelativeSource={RelativeSource Self}}" />
        <Setter Property="HorizontalContentAlignment" Value="Center" />
    </Style>
</ResourceDictionary>

但它不起作用。建议?其他解决方案? (如果相关的话,我正在使用 MVVM)。 提前致谢。

您必须将标签添加到文本框本身:

<TextBox Tag="{Binding Property1.IsAbilitato}"/>

如果您希望以下操作有效:

 <Setter Property="IsEnabled" Value="{Binding Path=Tag, RelativeSource={RelativeSource Self}}" />

但是如果您想将它添加到 UserControl 并希望应用所有 TextBox,则必须将其更改为:

<Setter Property="IsEnabled" Value="{Binding Path=Tag, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}" />