通用Windows应用程序:ListViewItem内部的两个按钮

时间:2016-06-14 21:50:18

标签: c# windows xaml uwp listviewitem

我的Listview.ItemTemplate的DataTemplate中有两个按钮。

使用Click事件自行访问每个文件都没有问题,但是,当我单击其中一个按钮时,我想更改其他按钮的前景色。如何在ListViewItem中获取另一个按钮(未单击)的实例?

1 个答案:

答案 0 :(得分:1)

由于您只想在单击其中一个按钮时更改其他按钮的前景色,因此您无需获取另一个按钮的实例。在这种情况下,使用Behaviors SDK可能是更好的选择。

以下是我验证过的xaml代码:

<Page
x:Class="ListViewWithTwoButtonDemo.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ListViewWithTwoButtonDemo"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:Interactivity="using:Microsoft.Xaml.Interactivity" xmlns:Interactions="using:Microsoft.Xaml.Interactions.Core"
mc:Ignorable="d">

<ListView Header="Medications" x:Name="myList" Background="White" HorizontalAlignment="Left" Width="400">
    <ListView.ItemTemplate>
        <DataTemplate>
            <Grid Width="400">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <TextBlock x:Name="medName" Text="{Binding Path=MedName}" TextWrapping="Wrap" />
                <TextBlock Grid.Column="1" x:Name="whatFor" Text="{Binding Path=WhatFor}" TextWrapping="Wrap" />
                <!--Use Behaviors SDK here, and no code behind is needed -->
                <Button Grid.Column="2" x:Name="btn1" Content="Button 1">
                    <Interactivity:Interaction.Behaviors>
                        <Interactions:EventTriggerBehavior EventName="Click" SourceObject="{Binding ElementName=btn1}">
                            <Interactions:ChangePropertyAction TargetObject="{Binding ElementName=btn2}" PropertyName="Foreground" Value="Green" />
                        </Interactions:EventTriggerBehavior>
                    </Interactivity:Interaction.Behaviors>
                </Button>
                <!--Use Behaviors SDK here, and no code behind is needed -->
                <Button Grid.Column="3" x:Name="btn2" Content="Button 2">
                    <Interactivity:Interaction.Behaviors>
                        <Interactions:EventTriggerBehavior EventName="Click" SourceObject="{Binding ElementName=btn2}">
                            <Interactions:ChangePropertyAction TargetObject="{Binding ElementName=btn1}" PropertyName="Foreground" Value="Green" />
                        </Interactions:EventTriggerBehavior>
                    </Interactivity:Interaction.Behaviors>
                </Button>
            </Grid>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
</Page>

以下是输出: enter image description here