ListView - 仅以编程方式选择索引

时间:2012-03-23 09:56:36

标签: c# wpf binding listbox viewbox

我正在尝试实现listbox(或listview):

<ListView ItemsSource="{Binding Players}" SelectedIndex="{Binding SelectedIndex}">

我的问题是,我想在代码隐藏中将选定的索引绑定到属性。 它仅适用于表单启动,但我需要禁用用户更改选择。 Selectin将仅在programmaticaly上更改。

感谢所有建议或解决方案:)

3 个答案:

答案 0 :(得分:1)

所以,工作解决方案:

private void playersList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (sender.GetType() == typeof(ListView))
    {
        (sender as ListView).SelectedIndex = GameObserver.Instance.core.SelectedIndex;
        e.Handled = true;
    }
}

在XAML中:

<ListView ItemsSource="{Binding Players}" SelectedIndex="{Binding SelectedIndex}" SelectionChanged="playersList_SelectionChanged">

有界财产:

private int selectedIndex = 1;
public int SelectedIndex
{
    get
    {
        return selectedIndex;
    }
}

答案 1 :(得分:0)

这里有两项任务:

以编程方式选择:WPF ListView Programmatically Select Item

禁用用户选择:WPF ListView turn off selection

答案 2 :(得分:-1)

没有设置

 Public Int SelectedIndex 
 {
      get { return selectedindex; }  
 }

 public void mysub()
 {
      selectedindex = 2; 
      NotifyPropertyChanged("SelectedIndex");
 }