【问题标题】:Wpf DataGrid bind selection from two Collections of same CountWpf DataGrid从两个相同计数的集合中绑定选择
【发布时间】:2013-06-04 07:48:59
【问题描述】:

我有List<Foo> FList<Bar> B,相同的计数。 将列 F.x 和 B.y 绑定到 WPF 中的相同 DataGrid 并维护从 DataGrid 到列表 F 和 B 的 OneWay 绑定的最干净/最好的方法是什么。

【问题讨论】:

    标签: c# wpf data-binding wpfdatagrid


    【解决方案1】:

    我会创建一个混合对象:

    课程:

        public class FooBar
        {
            public Foo F { get; set; }
            public Bar B { get; set; }
        }
    
        public class Foo
        {
            public int X { get; set; }
        }
    
        public class Bar
        {
            public int Y { get; set; }
        }
    

    视图模型:

        public class ViewModel : INotifyPropertyChanged
        {
            #region INotifyPropertyChanged Implementation
    
            public event PropertyChangedEventHandler PropertyChanged;
    
            protected void InvokePropertyChanged(string propertyName)
            {
                var e = new PropertyChangedEventArgs(propertyName);
                if (PropertyChanged != null) PropertyChanged(this, e);
            }
    
            #endregion
    
            public ViewModel()
            {
                this.FooBars.Add(new FooBar()
                {
                    B = new Bar(){Y = 30},
                    F = new Foo(){ X = 100}
                });
            }
    
            private ObservableCollection<FooBar> fooBars = new ObservableCollection<FooBar>();
            public ObservableCollection<FooBar> FooBars
            {
                get { return this.fooBars; }
                set
                {
                    this.fooBars = value;
                    InvokePropertyChanged("FooBars");
                }
            }
        }
    

    窗口返回代码:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new ViewModel();
        }
    }
    

    观点:

            <DataGrid ItemsSource="{Binding FooBars}" AutoGenerateColumns="False" >
                <DataGrid.Columns>
                    <DataGridTextColumn Binding="{Binding Path=F.X, Mode=TwoWay}" Header="This is FOO"></DataGridTextColumn>
                    <DataGridTextColumn Binding="{Binding Path=B.Y, Mode=TwoWay}" Header="This is BAR"></DataGridTextColumn>
                </DataGrid.Columns>
            </DataGrid>
    

    希望有帮助

    【讨论】:

    • 谢谢详细解释。我将尝试使用此解决方案的一部分来启用单向绑定表单 List 和 List
    猜你喜欢
    • 2018-07-16
    • 1970-01-01
    • 2023-03-07
    • 2015-11-28
    • 1970-01-01
    • 2015-04-27
    • 2011-06-13
    • 2016-02-28
    • 2014-10-05
    相关资源
    最近更新 更多