Reputation: 536
I have an array:
string Companies[,] = new string[100,7];
How can I put it to a dataGrid? I can't find any answear which works and I don't know where to start. I'm new to WPF, so can someone explain it to me, please?
Upvotes: 0
Views: 1715
Reputation: 731
Please use ItemsSource to assign data collections. I suggest you to read about MVVM implementation for WPF. But to start...
Create a class that implements INotifyPropertyChanged interface
public class Employer : INotifyPropertyChanged
{
private string nameField;
public string Name {
get { return nameField; }
set {
nameField= value;
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs("Name"));
}
}
}
private int idField;
public int Id {
get { return idField; }
set {
idField= value;
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs("Id"));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
Create a property
private ObservableCollection<Employer> employersField;
public ObservableCollection<Employer> Employers
{
get { return employersField; }
set {
employersField= value;
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs("Employers"));
}
}
}
Now let's say in a constructor you do
Employers = new ObservableCollection<Employer> {
new Employer {
Id = 0,
Name = "Mike"
},
new Employer {
Id = 1,
Name = "Dave"
}
}
Let's assume that you don't have view class so all your properties in a xaml related cs file. So you need to bind the DataContext
property of your dataGrid to your class and after assign ItemsSource to your property
<DataGrid DataContext = {Binding ElementName=YourControlName} ItemsSource="{Binding Employers}">
your content
</DataGrid >
YourControlName is a userControl name in xaml!
<UserControl x:Name="YourControlName" >
all stuff
</UserControl>
Look, this is a vary short overview, because I didn't show you how to bind your class properties to dataGrid columns and also how to bind selectedItem property to your property. But you can find many examples at stackoverflow as well as on the Internet. I just showed how to start and how things work in WPF
Upvotes: 2
Reputation: 1341
Constructor List of objects as below use it
class ViewModel
{
public string[,] Companies
{
get;
set;
}
public List<Example> Values
{
get;
set;
}
public ViewModel()
{
Companies = new string[2, 2] { { "sjhbfsjh", "jshbvjs" }, {"vsmvs", "nm vmdz" } };
Values = new List<Example>();
for (int i = 0; i < 2; i++)
{
Example ee = new Example();
ee.A = Companies[i, 0];
ee.B = Companies[i, 1];
Values.Add(ee);
}
}
}
public class Example
{
public string A
{
get;
set;
}
public string B
{
get;
set;
}
}
Then in your Xmal you can do as below
<DataGrid ItemsSource="{Binding Path=Values}"></DataGrid>
Set the data context in Xmal.cs
DataContext = new ViewModel();
Upvotes: 0