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

时间:2014-05-28 08:07:41

标签: c# .net silverlight silverlight-5.0 selectionchanged

我在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”和“txtblk1ShowStatus”。 我无法全局按下按钮和列表,因为此函数GenerateList(...)将被重复使用,而且它只是用c#编码(没有使用过xaml)。请让我知道怎么做如果您有其他方法可以解释如何做到这一点,但请详细解释您的代码

1 个答案:

答案 0 :(得分:1)

我认为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;