将样式从ResourceDictionary绑定到usercontrols

时间:2016-12-01 10:53:43

标签: wpf xaml binding resourcedictionary

我是wpf的新手,所以我正在寻找一个解决方案并解释为什么我的尝试解决方案无效。

这是我的理由。 我有几个UserControls。在每个中我都应用以下样式:

<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 ...

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

我尝试使用Tag属性,就像建议的here一样:

在我的用户控件中:

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

并在resourcedictionary中:

<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,如果它是相关的)。 提前谢谢。

1 个答案:

答案 0 :(得分:1)

您必须将标记添加到TextBox本身:

<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}}" />