I’m developing a small application which requires adding user-defined values to a grid. Problem is that even thought they add fine (I’ve checked in the debugger) they do not appear properly in the grid.
Screenshot:
.
Here is the code:
XAML:
<sdk:DataGrid x:Name="defaultValueDataGrid" AutoGenerateColumns="False" Height="150" Margin="0,0,10,0">
<sdk:DataGrid.Columns>
<sdk:DataGridTextColumn x:Name="valColumn" Binding="{Binding DefVal, Mode=OneWay}" IsReadOnly="True" Header="SomeHeader" Width="*" />
</sdk:DataGrid.Columns>
</sdk:DataGrid>
Definition of ItemSource collection and container class:
public ObservableCollection<DefaultValue> defaultValues;
//Class:
public class DefaultValue
{
public string DefVal;
public DefaultValue(string val)
{
this.DefVal = val;
}
}
Initialization in the page constructor:
this.defaultValues = new ObservableCollection<DefaultValue>();
this.defaultValueDataGrid.ItemsSource = this.defaultValues;
And lastly function which adds values:
private void AddNewDefaultValueBtn_Click(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrEmpty(this.newDefaultValueTxtBx.Text))
{
this.defaultValues.Add(new DefaultValue(this.newDefaultValueTxtBx.Text));
this.defaultValueDataGrid.ItemsSource = this.defaultValues;
}
}
Nothing fancy, right? Right, but it does not work and I will appreciate tips and help.
Ps. I have used this tutorial.
change
public string DefVal;to
public string DefVal {get;set;}Binding don’t work on member variables it works on properties
and you don’t need to reset the items source inside button click event
this.defaultValueDataGrid.ItemsSource = this.defaultValues;Changes in observable collection will directly change the DataGrid