简体   繁体   中英

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

I have a ListBox which creates a TextBlock for every item in my Dictionary and I need to create a click event and have the possibility to get anything from the TextBlock ( Tag in example).

Is this even possible? I found many similar questions, but nothing that would work for me.

My ListBox :

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

To simplify things lets say your dictionary is some thing like this :

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

and your model :

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

and you set the ListBox ItemSource from the code behind like this :

InitializeComponent();

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

You could simply handle the MouseDown event and retrieve the Tag property from the sender:

 <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>

the handler

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM