Background
I’m trying to bind my objects to a DataGrid
I have a list of PhoneVM objects. Each item in the list contains a list of StringBindingData. I need each item in StringBindingData to correspond to a different cell in a row of a DataGrid
Each item int he list corresponds to a different value for a user’s configuration, including Description and Value.
PhoneVM is defined as:
public class PhoneVM
{
public List<StringBindingData> StringBindingData { get; private set; }
public PhoneVM()
{
}
}
and StringBindingData is defined as:
public class StringBindingData : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public string Description { get; set; }
private string _value;
public string Value
{
get { return _value; }
set
{
OnPropertyChanged("Value");
}
}
public StringBindingData(string data, string description)
{
Value = data;
Description = description;
}
internal void OnPropertyChanged(string prop)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
}
The Description property of the first item in the StringBindingData list might contain “Name” and the Value property would contain the actual name. The Description property of the second item in the list might contain “Phone Number” and the Value property would contain the actual number.
Question
I want to get these to bind to a DataGrid. How can I do this?
What I have so far is an attempt to bind the first column to the Name
<DataGrid Name="phoneGrid" AutoGenerateColumns="False" Height="150" Width="Auto"
SelectionMode="Single" SelectionUnit="FullRow" Margin="10,10,0,0"
HorizontalAlignment="Left" VerticalAlignment="Top" SelectionChanged="phoneGrid_SelectionChanged">
<DataGrid.Columns>
<DataGridTextColumn Header="Name"
x:Name="columnPhoneNumber"
Binding="{Binding Path=Value}"
IsReadOnly="True">
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
With this in the code behind:
public Phone(List<PhoneVM> phoneVm)
{
InitializeComponent();
phoneGrid.DataContext = phoneVm;
}
But even looking at the code it’s obviously wrong. I don’t know how to specify for the DataContext that I want it to get the StringBindingData objects from phoneVm and take the data from that.
Is there something I need to add to the XAML to get this working? Is there something else I can add to the code? Do I need to change my data model?
As you say, you’re missing the binding to the
StringBindingDataproperty in your view model. Try addingItemsSource="{Binding StringBindingData}"to your DataGrid.