WPF Listview项目单击名称

时间:2013-07-05 22:19:17

标签: wpf listview selecteditem

我有一个包含5列的列表视图。在第一列中,我插入一个图像,我有一个事件MouseClicked事件。我想要完成的是当我点击第5行的图像时,获取第5行 - 第2列中的项目名称; 到目前为止,这是我的代码:

<ListView  x:Name="HistoryListB">
    <ListView.ItemContainerStyle>

        <Style TargetType="{x:Type ListViewItem}">

            <Setter Property="Background" Value="#FF515050"/>
            <Style.Triggers>
                <Trigger Property="Control.IsMouseOver" Value="true">
                    <Setter Property="Background" Value="#FF515050"/>
                    <Setter Property="BorderBrush" Value="#FF3B3A3A"/>
                </Trigger>
            </Style.Triggers>
        </Style>

    </ListView.ItemContainerStyle>
    <ListView.View>
        <GridView ColumnHeaderContainerStyle="{StaticResource myHeaderStyle}">

            <GridViewColumn Width="90" Header="Image" >

                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <Image Name="Favorite" Width="12" Height="12" Source="{Binding ImageSource}" MouseLeftButtonDown="Image_MouseLeftButtonDown" />
                    </DataTemplate>
                </GridViewColumn.CellTemplate>

            </GridViewColumn>

            <GridViewColumn Width="90" Header="Time Added" DisplayMemberBinding="{Binding Time}" />
            <GridViewColumn Width="110" Header="Status" DisplayMemberBinding="{Binding Status}"/>
            <GridViewColumn Width="290" Header="ItemTitle" DisplayMemberBinding="{Binding ItemTitle}"/>
            <GridViewColumn Width="50" Header="Duration" DisplayMemberBinding="{Binding Duration}"/>
        </GridView>
    </ListView.View>
</ListView>

我在listview中添加这样的项目。我有一个类和一个这样的列表:

public class HistoryItems
{
    public string Time { get; set; }
    public string Status { get; set; }
    public string ItemTitle { get; set; }
    public string Duration { get; set; }
    public ImageSource ImageSource { get; set; }
}

IList<HistoryItems> SHistoryItems { get; set; }

然后添加项目:

SHistoryItems = new List<HistoryItems>() {
    new HistoryItems () {
        Time = DateTime.Now.ToString("HH:mm:ss tt"),
        Status = "Started Playing : ",
        ItemTitle = StationL.StationName
    }
};

foreach (var item in SHistoryItems)
   HistoryListB.Items.Add(SHistoryItems);

在我的代码中,我想从同一行但第二列获取项目的名称:

private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    TextBlock1.Text = ?? THE NAME OF THE SECOND COLUMN IN THE SAME ROW ?? ;
}

1 个答案:

答案 0 :(得分:2)

您可以使用Tag的{​​{1}}属性来保存Image,然后您可以通过事件处理程序中的HistoryItem参数进行访问。

示例:

的Xaml:

sender

代码:

<GridViewColumn.CellTemplate>
    <DataTemplate>
        <Image Name="Favorite" Width="12" Height="12" Source="{Binding ImageSource}" Tag="{Binding}" MouseLeftButtonDown="Image_MouseLeftButtonDown" />
    </DataTemplate>
</GridViewColumn.CellTemplate>