是否可以使用包含控件的触发器更改DataTemplate中子项的属性?

时间:2009-07-21 14:23:57

标签: wpf listview triggers datatemplate

我想在IsMouseOver触发器中更改矩形的背景颜色,这可能吗?

<Window>
    <Window.Resources>
        <DataTemplate x:Key="StackListViewItemTemplate">
                <Grid>
                    <Rectangle RadiusX="5" RadiusY="5" >
                        <Rectangle.Fill>
                            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                                <GradientStop Color="#FF000000" Offset="0"/>
                                <GradientStop Color="{Binding Path=Events.Colour}" Offset="1"/>
                            </LinearGradientBrush>
                        </Rectangle.Fill>
                    </Rectangle>
                    <TextBlock FontSize="18pt" Grid.RowSpan="2" Text="{Binding Path=Events.Name}" HorizontalAlignment="Center" VerticalAlignment="Center"  />
                </Grid>
            </Grid>
        </DataTemplate>
    </Window.Resources>

    <Grid >
        <ListView ItemTemplate="{DynamicResource StackListViewItemTemplate}">
            <ListView.ItemContainerStyle>
                <Style TargetType="{x:Type ListViewItem}">
                    <Style.Triggers>
                        <Trigger Property="IsMouseOver" Value="true">
                            <!-- Here I want to set the background colour of the Rectangle in the DataTemplate -->
                        </Trigger>
                        <Trigger Property="IsSelected" Value="true">
                            <!-- Same here -->
                        </Trigger>
                    </Style.Triggers>

                </Style>
            </ListView.ItemContainerStyle>
        </ListView>
    </Grid>

</Window>

修改

<Setter Property="Background" Value="Yellow"/>

有没有办法将setter的Property值绑定到子控件?

2 个答案:

答案 0 :(得分:1)

我在模板

中使用datatrigger工作了
<DataTemplate x:Key="listItemTemplate" DataType="ListViewItem">
    <Grid>
        <Rectangle Name="myRectangle" RadiusX="5" RadiusY="5" >
            <Rectangle.Fill>
                <SolidColorBrush Color="Red" />
            </Rectangle.Fill>
        </Rectangle>
    </Grid>
    <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding Path=IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType=ListViewItem}}" Value="True">
            <Setter TargetName="myRectangle" Property="Fill" >
                <Setter.Value>
                    <SolidColorBrush Color="Green" />
                </Setter.Value>
            </Setter>
        </DataTrigger>
    </DataTemplate.Triggers>
</DataTemplate>

答案 1 :(得分:0)

是的,您应该能够做到这样的事情:

XAML Tutorial - Changing the Text Color on Mouse Over

...但当然是一个矩形。