我有List<Foo> F和List<Bar> B,同样的伯爵。将列 Fx 和 By 绑定到 WPF 中的同一个 DataGrid 并维护从 DataGrid 到列表 F 和 B 的 OneWay 绑定的最干净/最好的方法是什么。
1 回答
            3        
        
		
我会创建一个混合对象:
课程:
    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>
希望有帮助
于 2013-06-04T08:43:20.593   回答