繁体   English   中英

如何在WPF ListBox内的TextBlock中创建click事件并获取其Tag

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

我有一个ListBox ,它为我的Dictionary每个项目创建一个TextBlock ,并且我需要创建一个click事件,并有可能从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;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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