2012-09-17 45 views
1

我有一個WPF樣式,我正在應用列表框項目。目前,每個項目都綁定到一個KeyValuePair。我顯示ListBoxItem的內部在TextBlock中的關鍵,是否有可能將參數(綁定)傳遞給WPF樣式

<TextBlock Name="Label" Text="{Binding Key}" /> 

我想要做的是使樣式通用的,因此,如果數據不是KeyValuePair,(也許只是一個字符串),我可以綁定數據正確的TextBlock。

有沒有辦法將參數傳遞給Style或DataTemplate或使數據綁定通用?

我的風格:

<Style x:Key="ListBoxItemStyle" TargetType="ListBoxItem"> 
    <Setter Property="Template"> 
    <Setter.Value> 
     <ControlTemplate TargetType="ListBoxItem"> 
     <Border x:Name="Border" Padding="2" SnapsToDevicePixels="true" CornerRadius="4" BorderThickness="1"> 
      <TextBlock Name="Label" Text="{Binding Key}" /> 
     </Border> 
     <ControlTemplate.Triggers> 
      <MultiTrigger> 
      <MultiTrigger.Conditions> 
       <Condition Property="IsSelected" Value="True"/> 
      </MultiTrigger.Conditions> 
      <Setter TargetName="Border" Property="Background" Value="{StaticResource SelectionGradient}" /> 
      </MultiTrigger> 
     <ControlTemplate.Triggers> 
     </ControlTemplate> 
    </Setter.Value> 
    </Setter> 
</Style> 
+0

如何使用轉換器?你試過了嗎? – Damascus

+0

我還沒有嘗試過使用轉換器,但可能有效。我願意接受任何建議,以使其發揮作用。 –

回答

2

讓我給你舉一個簡單的例子。比方說,你TextBox包含一個數字,你希望它是一個紅色的背景,如果數字爲負,或綠色背景,如果> = 0

這是你寫的風格:

<TextBlock Text="{Binding Key}" > 
    <TextBlock.Style> 
    <Style TargetType="TextBox"> 
     <Setter Property="Background" Value="{Binding Key, Converter={StaticResource MyConverterResource}" /> 
    </Style> 
    </TextBlock.Style> 
</TextBlock> 

這裏是轉換器,你會寫:

public class MyConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     double source = (double)value; 
     return source < 0 ? Brushes.Red : Brushes.Green; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     // We don't care about this one here 
     throw new NotImplementedException(); 
    } 
} 

而且,訪問轉換器在XAML中,你就必須做到以下幾點,假設你的轉換器在命名空間MyNamespace

<Window xmlns:my="clr-namespace:MyNamespace"> 
    <Window.Resources> 
    <my:MyConverter x:Key="MyConverterResource"> 
    </Window.Resources? 
    <!-- Your XAML here --> 
</Window> 

(當然,你可以把這個在任何Resources,可以說,它是一個UserControl或其他) 這將允許你通過寫{StaticResource MyConverterResource}

這裏打電話給你的轉換器,你就會有一個條件樣式,轉換器根據一個參數決定將哪種顏色設置爲背景,在我的情況下,該值本身(但它可以是任何你想要的)

相關問題