如何让多个数据触发器对同一元素和属性起作用?
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding ElementName=RootGrid,Path=IsMouseOver}" Value="True">
<Setter TargetName="SelectionGrid" Property="Opacity" Value="0.5" />
</DataTrigger>
<DataTrigger Binding="{Binding ElementName=RootGrid,Path=IsMouseOver}" Value="False">
<Setter TargetName="SelectionGrid" Property="Opacity" Value="0.0" />
</DataTrigger>
<DataTrigger Binding="{Binding Selected}" Value="True">
<Setter TargetName="SelectionGrid" Property="Opacity" Value="1.0" />
</DataTrigger>
<DataTrigger Binding="{Binding Selected}" Value="False">
<Setter TargetName="SelectionGrid" Property="Opacity" Value="0" />
</DataTrigger>
</DataTemplate.Triggers>
请注意我如何定位SelectionGrid
的{{1}}属性。我怎样才能达到这个效果?这应该复制Windows 7具有的悬停选择框。因此,如果它都是Opacity
和Selected
,我希望它显示IsMouseOver
状态。
答案 0 :(得分:7)
您可以将MultiDataTrigger
或DataTrigger
与MultiBinding
和BooleanOrConverter一起使用。
但我认为解决您问题的最简单方法是使用MultiBinding
Opacity
绑定Selected
和IsMouseOver
<DataTemplate>
<Grid x:Name="SelectionGrid">
<Grid.Opacity>
<MultiBinding Converter="{StaticResource OpacityConverter}">
<Binding RelativeSource="{RelativeSource Self}" Path="IsMouseOver"/>
<Binding Path="Selected"/>
</MultiBinding>
</Grid.Opacity>
</Grid>
<!-- ... -->
</DataTemplate>
在OpacityConverter中,您决定Opacity
值
public class OpacityConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool isMouseOver = (bool)values[0];
bool selected = (bool)values[1];
if (selected == true)
{
return 1.0;
}
else if (isMouseOver == true)
{
return 0.5;
}
return 0.0;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
修改:您可以使用DataTrigger
和MultiDataTrigger
<DataTemplate>
<Grid x:Name="SelectionGrid"
Opacity="0"
Background="Blue">
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=Selected}" Value="True">
<Setter TargetName="SelectionGrid" Property="Opacity" Value="1.0"/>
</DataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding ElementName=SelectionGrid, Path=IsMouseOver}" Value="True"/>
<Condition Binding="{Binding Path=Selected}" Value="False"/>
</MultiDataTrigger.Conditions>
<Setter TargetName="SelectionGrid" Property="Opacity" Value="0.5"/>
</MultiDataTrigger>
</DataTemplate.Triggers>
</DataTemplate>