Wpf DataGrid从相同计数的两个集合中绑定选择

本文关键字:两个 集合 选择 绑定 DataGrid Wpf | 更新日期: 2023-09-27 18:16:44

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

Wpf DataGrid从相同计数的两个集合中绑定选择

我将创建一个混合对象:

类:

    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>

希望有帮助