【发布时间】:2013-06-04 07:48:59
【问题描述】:
我有List<Foo> F 和List<Bar> B,相同的计数。
将列 F.x 和 B.y 绑定到 WPF 中的相同 DataGrid 并维护从 DataGrid 到列表 F 和 B 的 OneWay 绑定的最干净/最好的方法是什么。
【问题讨论】:
标签: c# wpf data-binding wpfdatagrid
我有List<Foo> F 和List<Bar> B,相同的计数。
将列 F.x 和 B.y 绑定到 WPF 中的相同 DataGrid 并维护从 DataGrid 到列表 F 和 B 的 OneWay 绑定的最干净/最好的方法是什么。
【问题讨论】:
标签: c# wpf data-binding wpfdatagrid
我会创建一个混合对象:
课程:
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>
希望有帮助
【讨论】: