如何在c#中实现自己的SelectionChangedEventHandler

本文关键字:实现 自己的 SelectionChangedEventHandler | 更新日期: 2023-09-27 18:05:35

我在silverlight工作,在一个非常奇怪的情况下,我需要实现我自己的SelectionChangedEventHandler处理函数。这样做的原因是:

我的情况是这样的:

    private static Grid GenerateList(Parameter param, int LoopCount, Grid g)
    {
        Grid childGrid = new Grid();
        ColumnDefinition colDef1 = new ColumnDefinition();
        ColumnDefinition colDef2 = new ColumnDefinition();
        ColumnDefinition colDef3 = new ColumnDefinition();
        childGrid.ColumnDefinitions.Add(colDef1);
        childGrid.ColumnDefinitions.Add(colDef2);
        childGrid.ColumnDefinitions.Add(colDef3);
        TextBlock txtblk1ShowStatus = new TextBlock();
        TextBlock txtblkLabel = new TextBlock();
        ListBox lines = new ListBox(); 
        ScrollViewer scrollViewer = new ScrollViewer();            
        scrollViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
        lines.ItemsSource = param.Component.Attributes.Items;
        scrollViewer.Content = lines; 
        Grid.SetColumn(scrollViewer, 1);
        Grid.SetRow(scrollViewer, LoopCount);
        childGrid.Children.Add(scrollViewer);
        lines.SelectedIndex = 0;
        lines.SelectedItem = param.Component.Attributes.Items;// This items contains 1000000,3 00000, and so on.
        lines.SelectionChanged += new SelectionChangedEventHandler(List_SelectionChanged);
       // lines.SelectionChanged += new SelectionChangedEventHandler(List_SelectionChanged(lines, txtblk1ShowStatus));
        lines.SelectedIndex = lines.Items.Count - 1;

        Grid.SetColumn(txtblk1ShowStatus, 2);
        Grid.SetRow(txtblk1ShowStatus, LoopCount);
        childGrid.Children.Add(txtblk1ShowStatus);
        g.Children.Add(childGrid);
        return (g);
    }
   static void List_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        MessageBox.Show("clist   _SelectionChanged1");  
      //The problem is line below because i am "lines" and "txtblk1ShowStatus" are not in the 
      //scope of this function and i cannot declare them globally.
        txtblk1ShowStatus.Text = lines[(sender as ListBox).SelectedIndex]; 
    }  

在这里你可以看到我没有访问List_SelectionChanged(object sender, SelectionChangedEventArgs e)函数中的"lines"answers"txtblk1ShowStatus"。并且我不能全局声明按钮和列表,因为这个函数GenerateList(...)将被重用,它只是用c#编码(没有使用xaml)。请告诉我怎么做如果你有其他的方法请告诉我怎么做但是请详细解释你的代码

如何在c#中实现自己的SelectionChangedEventHandler

我认为lambda表达式将帮助您解决您的问题(您可能需要编辑它):

lines.SelectedIndex = 0;
lines.SelectedItem = param.Component.Attributes.Items;// This items contains 1000000,3 00000, and so on.
lines.SelectionChanged += (o,e) => {
    MessageBox.Show("clist   _SelectionChanged1");
    txtblk1ShowStatus.Text = lines.SelectedItem.ToString();
};
lines.SelectedIndex = lines.Items.Count - 1;