如何在 WPF ListBox 中的 TextBlock 中创建点击事件并获取其标签

How to create click event in TextBlock inside WPF ListBox and get its Tag

我有一个 ListBox,它为我的 Dictionary 中的每个项目创建一个 TextBlock,我需要创建一个点击事件并有可能从 TextBlock(例如Tag)。

这可能吗?我发现了很多类似的问题,但没有一个对我有用。

我的ListBox:

<ListBox x:Name="listbox">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Tag="{Binding Path=Key}"
                           Text="{Binding Path=Value.ImieNazwisko}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

为简化起见,假设您的字典是这样的:

public Dictionary<string,MyItem> MyDictionary { get; set; }

和你的模特:

public class MyItem
    {
        public string ImieNazwisko { get; set; }    
    }

然后您从后面的代码中设置 ListBox ItemSource 如下:

InitializeComponent();

   MyDictionary = new Dictionary<string, MyItem>()
            {
                {"key1",new MyItem() {ImieNazwisko = "one"} },
                {"key2",new MyItem() {ImieNazwisko = "two"} }
            };
   Listbox.ItemsSource = MyDictionary;

您可以简单地处理 MouseDown 事件并从发件人那里检索 Tag 属性:

 <ListBox x:Name="Listbox" Margin="225,0,0,0" >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Tag="{Binding Path=Key}" Text="{Binding Path=Value.ImieNazwisko}" MouseDown="UIElement_OnMouseDown"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

处理程序

 private void UIElement_OnMouseDown(object sender, MouseButtonEventArgs e)
    {
        var tag=(sender as TextBlock).Tag;
    }