WPF的ListBox控件当中IsSynchronizedWithCurrentItem说明

    WPF的ListBox控件继承自一个叫Selector的类,Selector是个抽象(abstract)类,意味着Selector是个无法实例化的类,而ListBox继承自Selector类,也就意味着ListBox实现了好多Selector类当中的成员或方法。

    今天简单介绍下ListBox的属性IsSynchronizedWithCurrentItem,其实这个属性是继承自Selector的。

    IsSynchronizedWithCurrentItem如果为true,意味着用户在界面上用鼠标选择一个项(每次选择会实时地改变SelectedItem属性,这个属性其实也是来自Selector类)会立即更新(同步)到对象集合(ListBox的Items属性)的当前项(Items对象的CurrentItem属性),反之亦成立。说这么多废话,还是画个图吧:


    

如果IsSynchronizedWithCurrentItem的值是false,则两者不会相互影响。

下面举个例子说明下吧:

XMAL代码:

    <StackPanel>
        <ListBox Margin="5" Name="firstListBox" DisplayMemberPath="FirstName" IsSynchronizedWithCurrentItem="True"></ListBox>
        <ListBox Margin="5" Name="secondListBox" DisplayMemberPath="FirstName" IsSynchronizedWithCurrentItem="True"></ListBox>
    </StackPanel>

c#后台代码:

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Person(string f,string l)
        {
            FirstName = f;
            LastName = l;
        }
    }

    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public static ObservableCollection<Person> persons { get; set; } = new ObservableCollection<Person>();
        public MainWindow()
        {
            persons.Add(new Person("MeiLin","Xu"));
            persons.Add(new Person("JieShi", "Jiang"));
            InitializeComponent();
            firstListBox.ItemsSource = persons;
            secondListBox.ItemsSource = persons;
        }
    }

我们可以看到下面的效果:


仔细看上图,在任何一个ListBox中用鼠标选择一项,在另一个ListBox中的选择也会跟着变。

猜你喜欢

转载自blog.csdn.net/qq_16587307/article/details/79589882