在每个ListBox项中添加Name属性

时间:2013-08-06 12:17:44

标签: c# wpf binding listbox listboxitem

我有一个WPF项目,其中我有Resource Dictionary我存储我的样式。在这本词典中,我有ListBoxItem Template,看起来像这样。

    <DataTemplate x:Key="GenreStyle">
    <Grid Width="150" Height="150" Background="Transparent">
        <Image x:Name="GenreImage" Tag="{Binding Genre}" RenderOptions.BitmapScalingMode="HighQuality" Source="{Binding GenreSource}" Width="140" Height="140" MouseEnter="GenreImage_MouseEnter" MouseLeave="GenreImage_MouseLeave" MouseLeftButtonDown="GenreImage_MouseLeftButtonDown" MouseLeftButtonUp="GenreImage_MouseLeftButtonUp"/>
    </Grid>
</DataTemplate>

现在我要做的是,当我点击每个项目时,请阅读图像Tag。 我现在正在做的是:

private void StationsListLB_PreviewMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
    var item = ItemsControl.ContainerFromElement(StationsListLB, e.OriginalSource as DependencyObject) as ListBoxItem;
    if (item != null)
    {
       MessageBox.Show(??????);
    }
}

1 个答案:

答案 0 :(得分:0)

好的想通了。我只需抓住System.Windows.Input.MouseButtonEventArgs。 然后非常简单:

private void StationsListLB_PreviewMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
    var item = ItemsControl.ContainerFromElement(StationsListLB, e.OriginalSource as DependencyObject) as ListBoxItem;
    if (item != null)
    {
        var opa = e.OriginalSource as System.Windows.Controls.Image;
        MessageBox.Show(opa.Tag.ToString());
    }
}