2012-09-17 47 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}

这里打电话给你的转换器,你就会有一个条件样式,转换器根据一个参数决定将哪种颜色设置为背景,在我的情况下,该值本身(但它可以是任何你想要的)

相关问题