我的问题是这篇文章的后续问题:What are the different triggers in WPF?
我想设置一个触发器,如果该项是listview中的第一个,则触发(因此我可以添加额外的文本)。我应该使用哪种类型的触发器?
这是我的代码:
<ListView Grid.Row="1" Grid.Column="2" Name="contactList" Margin="0,0,0,0">
<ListView.ItemTemplate>
<DataTemplate>
<WrapPanel>
<TextBlock Text="{Binding Name}" />
<TextBlock>
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<Trigger <!-- what do I have to put here so it triggers when the item is the first one in the list? -->>
<Setter Property="Text" Value=" - this is the first item in the list!!"/>
<Setter Property="Foreground" Value="#7f8c8d"/>
</Trigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</WrapPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
答案 0 :(得分:0)
你必须为这个坏孩子使用DataTrigger
MultiBinding
和转换器。看看吧。
首先,你的转换器......
class IsFirstItemConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
ObservableCollection<NamedObject> col = (ObservableCollection<NamedObject>)values[0];
if (col[0].Equals(values[1]))
return true;
else
return false;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
现在在App.xaml中引用它...
<local:IsFirstItemConverter x:Key="isFirstItem"/>
现在为肉...
<ListView x:Name="lv" ItemsSource="{Binding Items}">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock>
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<!--Text property moved to here-->
<Setter Property="Text" Value="{Binding Name}"/>
<Style.Triggers>
<DataTrigger Value="True">
<DataTrigger.Binding>
<MultiBinding Converter="{StaticResource isFirstItem}">
<MultiBinding.Bindings>
<Binding ElementName="lv" Path="ItemsSource"/>
<Binding/>
</MultiBinding.Bindings>
</MultiBinding>
</DataTrigger.Binding>
<Setter Property="Text" Value="First item"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
请注意,您必须将Text
属性的setter移动到样式中。由于控件中的显式声明会覆盖样式中的任何属性设置器,因此除非按图所示移动它,否则您将看不到触发器的效果。希望这有帮助!