如果两个控件都绑定到同一个源(ObservableCollection)集合视图时,该对象会自动绑定到该视图的 CurrentItem。请注意,CollectionViewSource 对象会自动同步货币与所选内容。如果列表控件没有像示例中那样绑定到 CollectionViewSource 对象,则您需要将其 IsSynchronizedWithCurrentItem 属性设置为 true 以达到此目的。
在列表ListBox控件中绑定一个ObservableCollection后,点击列表项时,会自动设置CurrentItem,同时其他控件如果也绑定了该ObservableCollection的话,便会根据CurrentItem重新绑定数据。
下面举个例子说明下吧:
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; } }
我们可以看到下面的效果:
标签:控件,ObservableCollection,string,persons,绑定,public,IsSynchronizedWithCurrentItem,W From: https://www.cnblogs.com/cdaniu/p/16793548.html