【WPF】Tabcontrol的IsSynchronizedWithCurrentItem属性

如果两个控件都绑定到同一个源(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;
        }
    }
复制代码

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

 

 

 

 

posted @   小林野夫  阅读(117)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
历史上的今天:
2021-10-15 关键词|上下文关键词
原文链接:https://www.cnblogs.com/cdaniu/
点击右上角即可分享
微信分享提示