Reputation: 6977
I have List<Foo> F
and List<Bar> B
, same Count.
What is the cleanest/nicest way to bind columns F.x and B.y to same DataGrid in WPF and mantain OneWay binding from DataGrid to lists F and B.
Upvotes: 1
Views: 410
Reputation: 658
I Would create a hybrid object:
The classes:
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; }
}
The view model:
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");
}
}
}
The window back code:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
}
The view:
<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>
Hope that helps
Upvotes: 3