2015-08-16 73 views
1

在我的节目我用WPF 列表框显示单选按钮。有两个按钮“添加帖子”和“删除帖子”。添加/删除单选

我可以补充项目,但有两个问题:

1)如何定位添加对新项目后,光标(点)?

2)如何删除选定的项目并将光标定位到上一个?

enter image description here

// Add element 
private void Button_Click_4(object sender, RoutedEventArgs e) 
{ 
     RadioButton obj = new RadioButton(); 
     obj.Content = "Group " + ++numberOfGroups; 
     ListBox1.Items.Add(obj); 
} 

// Remove element 
private void Button_Click_5(object sender, RoutedEventArgs e) 
{ 
    //.. 
} 

编辑1:

感谢的答案,但你的代码工作正常的列表元素。通过位置光标我的意思是,我需要选择一个单选按钮,而不是列表中的元素。可能它会随着这个截图更清晰:

enter image description here

+1

由C#代码隐藏添加或删除项目将在每个'Page_load()'中完成,这意味着用户不会看到它完成 - 他只会在加载操作之后看到固定列表,而在旧操作之前会看到固定列表。 –

+1

@ A.Abramov它的WPF不是ASP.net – Shaharyar

+0

这是不是很清楚你想在这里实现什么。 “定位光标”的意思是“自动移动鼠标光标”吗? –

回答

2

如果通过定位光标意味着一个项目的选择。

// Add element 
private void Button_Click_4(object sender, RoutedEventArgs e) 
{ 
    //add new item 
    RadioButton obj = new RadioButton(); 
    obj.Content = "Group " + ++numberOfGroups; 
    ListBox1.Items.Add(obj); 

    //select last item 
    int LastItemIndex = ListBox1.Items.Count - 1; 
    ListBox1.SelectedItem = ListBox1.Items.GetItemAt(LastItemIndex); 
} 

// Remove element 
private void Button_Click_5(object sender, RoutedEventArgs e) 
{ 
    //delete selected item 
    ListBox1.Items.RemoveAt(ListBox1.SelectedIndex); 

    //select last item 
    int LastItemIndex = ListBox1.Items.Count - 1; 
    ListBox1.SelectedItem = ListBox1.Items.GetItemAt(LastItemIndex); 
} 
1

如果“将光标定位”是指“选择项”,然后::您可以通过获取​​ListBox的最后一个指标很容易做到这一点

private void Button_Click_4(object sender, RoutedEventArgs e) 
    { 
     RadioButton obj = new RadioButton(); 
     obj.Content = "Group " + ++numberOfGroups; 
     ListBox1.Items.Add(obj); 
     ListBox1.SelectedItem = obj; 
     obj.IsChecked = true; 
     ListBox1.Focus(); 
    } 

    private void Button_Click_5(object sender, RoutedEventArgs e) 
    { 
     if (ListBox1.SelectedItem != null) 
     { 
      int position = ListBox1.Items.IndexOf(ListBox1.SelectedItem); 

      ListBox1.Items.Remove(ListBox1.SelectedItem); 

      if (ListBox1.Items.Count == 0) return; 

      if (position == 0) 
      { 
       ListBox1.SelectedItem = ListBox1.Items[0]; 
      } 
      else 
      { 
       ListBox1.SelectedItem = ListBox1.Items[position - 1]; 
      } 

      (ListBox1.SelectedItem as RadioButton).IsChecked = true; 
     } 
    }