WP如何通过代码给ListBox的Item添加事件?
ListBox的xaml代码如下:
<ListBox Margin="0,170,0,0" Name="UnreadList" Foreground="#FF019B9B" Background="Transparent"></ListBox>
foreach (Unread data in _unreadEntries)
{
UnreadList.Items.Add(
new TextBlock
{
Text=data.nickname,
FontSize=20,
Margin=new Thickness(110,-100,256,60),
Width=100,
Height=30,
Name = "Nickname" + data.uid,
}
);
UnreadList.Items.Add(
new TextBlock
{
Text = data.type,
FontSize = 20,
Margin = new Thickness(210,-100, 0, 60),
Width = 256,
Height = 30,
Name = "Type" + data.uid,
}
);
}
[解决办法]
UnreadList.SelectionChanged += UnreadList_SelectionChanged;
foreach (Unread data in _unreadEntries)
{
UnreadList.Items.Add(
new TextBlock
{
Text=data.nickname,
FontSize=20,
Margin=new Thickness(110,-100,256,60),
Width=100,
Height=30,
Name = "Nickname" + data.uid,
Tag=data.uid,
}
);
UnreadList.Items.Add(
new TextBlock
{
Text = data.type,
FontSize = 20,
Margin = new Thickness(210,-100, 0, 60),
Width = 256,
Height = 30,
Name = "Type" + data.uid,
Tag=data.uid,
}
);
}
void UnreadList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var obj = ((ListBox)sender).SelectedItem;
string label=String.Empty;
if (obj==null) return;
if ((obj as Image) != null)
{
Image temp = (Image)obj;
label = temp.Tag.ToString();
}
else if ((obj as TextBlock) != null)
{
TextBlock temp = (TextBlock)obj;
label = temp.Tag.ToString();
}
else
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Error type:"+obj.GetType().ToString());
});
}
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(label);
});
}