[英]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). 我有一个
ListBox
,它为我的Dictionary
每个项目创建一个TextBlock
,并且我需要创建一个click事件,并有可能从TextBlock
获取任何内容(示例中为Tag
)。
Is this even possible? 这有可能吗? I found many similar questions, but nothing that would work for me.
我发现了许多类似的问题,但没有任何对我有用的问题。
My ListBox
: 我的
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 : 然后从后面的代码中设置
ListBox
ItemSource
,如下所示:
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: 您可以简单地处理
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>
the handler 处理程序
private void UIElement_OnMouseDown(object sender, MouseButtonEventArgs e)
{
var tag=(sender as TextBlock).Tag;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.