2016-12-01 60 views
0

我是wpf的新手,所以我正在寻找解决方案并解释为什么我的尝试解决方案无法正常工作。从ResourceDictionary到usercontrols的绑定样式

这是我的情况。 我有几个用户控件。在它们中的每一个中,我应用以下样式:

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

基于资源字典中定义的样式。 它工作正常。 但要注意,对于每一个用户控件,以前的代码是相同的,除了绑定属性,那将是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,如果它是相关的)。 在此先感谢。

+0

你是否已经将该资源文件应用到您的app.xaml? –

+0

是的,我做到了。它适用于其他的东西。 – Nikzeno

回答

1

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

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

,如果你想工作情况如下:

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

但是如果你想将其添加到用户控件,并希望所有TextBox的应用到那么你必须改变它:

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