首页 文章

将一个列表框listboxitem与另一个列表框绑定

提问于
浏览
0

我是C#WPF的新手,所以请忍受我的问题 . 我有两个列表框(listbox1和listbox2),其中listbox1中的项目将在运行时通过用户输入添加或删除 . 我希望listbox2通过绑定方法相应地显示其listboxitem .

例如,如果listbox1最初有5个项目,我希望listbox2显示相同的5个项目 . 如果在运行时添加或删除listbox1中的项目,我希望listbox2显示与listbox1相同的数据(项目) .

有人可以给我一个提示吗?提前致谢 .

1 回答

  • 0

    我对你的情况知之甚少但是假设你有以下数据模型保存你的数据,实现了INotifyPropertyChangedInterface:

    public class A : INotifyPropertyChanged 
    {
        public String SomeProperty {....}
        ...
    }
    

    然后你有一个包含你的项目的viewmodel,让它从som baseclass继承 . 我推荐 Galasoft MVVM Light 并进一步扩展您的需求 . OnPropertyChanges调用 INotifyPropertyChanged . 无论如何,我在这里切了一些角落:

    public YourViewModel : YourViewModelBase 
    {
       private ObservableCollection<A> yourItems_ = new ObservableCollection<A>();
       public ObservableCollection YourItems {
           get { return yourItems_;}
           set { if( yourItems_!=value ) {
                   _yourItems = value;
                   OnPropertyChanged();
                 }
                 return _yourItems;
           }
    
          }
    }
    

    然后在你的xaml中,你只需绑定到属性YourItems并在你的数据模型上设置displaymember .

    <UserControl.....>
     <UserControl.DataContext><vm:YourViewModel/></UserControl.DataContext>
        <Grid>
          <Grid.RowDefinition="Auto"/>
          <Grid.RowDefinition="Auto"/>
          <Grid.RowDefinition="*"/>
        <Grid/>
        <ListBox Grid.RowDefinition="0" ItemsSource="{Binding YourItems}" DisplayMemberPath="SomeProperty"/>
        <ListBox Grid.RowDefinition="1" ItemsSource="{Binding YourItems}" DisplayMemberPath="SomeProperty"/>
     </UserControl>
    

    请注意,您可以编辑模板以获取项目的另一个可视化表示,使用DisplayMamberPath只需将其作为字符串添加到列表框演示文稿中,除非您有一个覆盖.ToString()的类;方法 .

    如果您需要过滤相同的itemssource,请查看 ICollectionView .

    希望能帮助到你,

    Cheeers,

    了Stian

相关问题