【问题标题】:Binding one listbox listboxitem from another listbox从另一个列表框绑定一个列表框列表框项
【发布时间】:2014-09-09 06:23:46
【问题描述】:

我对 C# WPF 很陌生,所以请耐心等待我的问题。 我有两个列表框(listbox1 和 listbox2),其中 listbox1 中的项目将在运行时通过用户输入添加或删除。我希望listbox2通过绑定方法相应地显示它的listboxitem。

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

有人可以给我小费吗? 提前致谢。

【问题讨论】:

  • 将两个列表框绑定到模型中的同一个列表

标签: c# wpf listbox


【解决方案1】:

我对您的情况知之甚少,但可以说您有以下数据模型来保存您的数据,实现 INotifyPropertyChangedInterface:

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

然后你有一个包含你的项目的视图模型,让它从 som 基类继承。我推荐 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 并在数据模型上设置显示成员。

 <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(); 的类;方法。

如果您需要过滤相同的项目来源,请查看 ICollectionView

希望对你有帮助,

干杯,

斯蒂安

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多