我正在尝试优化此代码(用于C#(WPF)中的重复过程)。有没有机会创建一个方法,完成所有这些代码?只是有点聪明?我不想将此代码复制并粘贴到DoMyCode()
中。我的问题是,我点击了ListViewItems
。每个ListViewItem
执行相同的操作(仅与另一个Label
)。
private void listViewItem_Group0_Selected(object sender, RoutedEventArgs e)
{
label_Position.Content = label_Group0.Content.ToString();
SetDataGridItems(label_Group0.Content.ToString());
}
private void listViewItem_Group1_Selected(object sender, RoutedEventArgs e)
{
label_Position.Content = label_Group1.Content.ToString();
SetDataGridItems(label_Group1.Content.ToString());
}
private void listViewItem_Group2_Selected(object sender, RoutedEventArgs e)
{
label_Position.Content = label_Group2.Content.ToString();
SetDataGridItems(label_Group2.Content.ToString());
}
private void listViewItem_Group3_Selected(object sender, RoutedEventArgs e)
{
label_Position.Content = label_Group3.Content.ToString();
SetDataGridItems(label_Group3.Content.ToString());
}
private void listViewItem_Group4_Selected(object sender, RoutedEventArgs e)
{
label_Position.Content = label_Group4.Content.ToString();
SetDataGridItems(label_Group4.Content.ToString());
}
我的XAML代码如下所示:
<ListViewItem Selected="listViewItem_Group0_Selected">
<DockPanel>
<Image Source="/Apptivities;component/Images/interessenten_.png" Stretch="None" />
<Label Content="Interessenten Sponsoren" Name="label_Group0" />
</DockPanel>
</ListViewItem>
<ListViewItem Selected="listViewItem_Group1_Selected">
<DockPanel>
<Image Source="/Apptivities;component/Images/interessenten_.png" Stretch="None" />
<Label Content="Interessenten Teilnehmer" Name="label_Group1" />
</DockPanel>
</ListViewItem>
<ListViewItem Selected="listViewItem_Group2_Selected">
<DockPanel>
<Image Source="/Apptivities;component/Images/keine_kooperation.png" Stretch="None" />
<Label Content="Keine Kooperation" Name="label_Group2" />
</DockPanel>
</ListViewItem>
<ListViewItem Selected="listViewItem_Group3_Selected">
<DockPanel>
<Image Source="/Apptivities;component/Images/potenzielle_.png" Stretch="None" />
<Label Content="Potenzielle Sponsoren" Name="label_Group3" />
</DockPanel>
</ListViewItem>
<ListViewItem Selected="listViewItem_Group4_Selected">
<DockPanel>
<Image Source="/Apptivities;component/Images/potenzielle_.png" Stretch="None" />
<Label Content="Potenzielle Teilnehmer" Name="label_Group4" />
</DockPanel>
</ListViewItem>
你知道吗,怎么做?
答案 0 :(得分:2)
您可以使用基于发件人对象的一种方法轻松转换所有代码
private void listViewItem_Group_Selected(object sender, RoutedEventArgs e)
{
ListViewItem lv = sender as ListViewItem;
DockPanel dockpanel = (lv.Content) as DockPanel;
Label label = (dockpanel.Children[1]) as Label;
label_Position.Content = label.Content.ToString();
SetDataGridItems(label.Content.ToString());
}
将所有选定事件更改为公共事件“listViewItem_Group_Selected”,并且由于dockpanel是ListViewItem的子项,可以通过迭代dockpanel子控件来读取Label。
答案 1 :(得分:0)
您可以将前端(XAML / WinForm)中的所有listviewitem选定事件引用到一个代码隐藏方法,然后使用sender对象区分它们。