Search code examples
c#wpflistboxtextblock

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>

Solution

  • 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;
        }