2016-12-01 48 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}}" />