代码之家  ›  专栏  ›  技术社区  ›  Robert Höglund

如何同步列表框的SelectedItem?

  •  2
  • Robert Höglund  · 技术社区  · 16 年前

    public interface ISelectable : INotifyPropertyChanged
    {
        event EventHandler IsSelected;
        bool Selected { get; set; }
        string DisplayText { get; }
    }
    

    ISelectable selectable = (ISelectable)e.AddedItems[0];
    selectable.Selected = true;
    

    我的问题是,当我使用代码选择对象时,我无法获取ListBox来更改所选项目。我使用数据模板以不同的颜色显示所选对象,这意味着所有内容都正确显示。但是ListBox将用户单击的最后一个对象作为SelectedItem,这意味着如果不先选择列表中的另一个对象,则无法单击该项。

    有人知道怎么解决这个问题吗?我非常确信,通过编写一些自定义代码来处理鼠标和键盘事件,我可以实现我想要的,但我宁愿不这样做。我尝试将SelectedItem属性添加到集合中,并将其绑定到ListBox的SelectItem属性,但没有成功。

    3 回复  |  直到 16 年前
        1
  •  4
  •   Ian Oakes    16 年前

    也可以通过将ListBoxItem.IsSelected数据绑定到所选属性来完成此操作。其思想是在创建每个ListBoxItem时为其设置绑定。这可以使用针对为ListBox生成的每个ListBoxItems的样式来完成。

    这样,当列表框中的项目被选中/取消选中时,相应的选定属性将被更新。同样,在代码中设置选定的属性将反映在列表框中

    <List.Resources>
        <Style TargetType="ListBoxItem">
            <Setter 
                Property="IsSelected" 
                Value="{Binding 
                            Path=DataContext.Selected, 
                            RelativeSource={RelativeSource Self}}" 
                />
        </Style>
    </List.Resources>
    
        2
  •  1
  •   Pondidum    16 年前

    您是否查看了列表框的SelectedItemChanged和SelectedIndexChanged事件?

    无论选择如何选择,只要选择发生更改,都应触发这些。

        3
  •  0
  •   Sorskoot    16 年前

    private bool _Selected;
            public bool Selected
            {
                get
                {
                    return _Selected;
                }
                set
                {
                    if (PropertyChanged != null)                
                        PropertyChanged(this, new PropertyChangedEventArgs("Selected"));
    
                    _Selected = value;
                }
            }
    

    我尝试了以下代码:

    public ObservableCollection<testClass> tests = new ObservableCollection<testClass>();
    
            public Window1()
            {
                InitializeComponent();
                tests.Add(new testClass("Row 1"));
                tests.Add(new testClass("Row 2"));
                tests.Add(new testClass("Row 3"));
                tests.Add(new testClass("Row 4"));
                tests.Add(new testClass("Row 5"));
                tests.Add(new testClass("Row 6"));
                TheList.ItemsSource = tests;
            }
    
            private void Button_Click(object sender, RoutedEventArgs e)
            {
                tests[3].Selected = true;
                TheList.SelectedItem = tests[3];
            }
    

    其中testClass实现了ISelectable。

    <ListBox Grid.Row="0" x:Name="TheList"></ListBox>        
    <Button Grid.Row="1" Click="Button_Click">Select 4th</Button>
    

    我希望这有帮助。