I'm working a project in which I need to bind a DataGrid to an observable collection of the following structure :
public struct TranslationEntry
{
public string LangCode { get; set; }
public string LangName { get; set; }
public string Translation { get; set; }
}
That collection is a property of a class called TranslationModel. I'm trying to edit the content of that collection with a DataGrid. Here is the XAML :
<DataGrid x:Name="translationGrid" Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2" ItemsSource="{Binding Translations, UpdateSourceTrigger=PropertyChanged}"
AutoGenerateColumns="false" IsSynchronizedWithCurrentItem="true">
<DataGrid.Columns>
<DataGridTextColumn Header="Language" Width="auto" Binding="{Binding Path=LangName, UpdateSourceTrigger=PropertyChanged}" IsReadOnly="True"/>
<DataGridTextColumn Header="Translation" Width="*" Binding="{Binding Path=Translation, UpdateSourceTrigger=PropertyChanged}"/>
</DataGrid.Columns>
</DataGrid>
And the CS:
public partial class TextTranslatorWindow : Window
{
public TextTranslatorWindow(TranslationModel translationModel)
{
InitializeComponent();
TranslationModel = translationModel;
grid.DataContext = TranslationModel;
}
private TranslationModel _translationModel;
public TranslationModel TranslationModel
{
get { return _translationModel; }
set { _translationModel = value; }
}
}
The TranslationModel
is just an empty class for now :
public class TranslationModel
{
public TranslationModel()
{
}
private ObservableCollection<TranslationEntry> _translations = new ObservableCollection<TranslationEntry>();
public ObservableCollection<TranslationEntry> Translations
{
get { return _translations; }
set { _translations = value; }
}
}
The binding seems to work as the items are displayed: Editable Rows
But it turns out that the Translation collection is not updated. The previous values are kept. The data context of the grid (in which the DataGrid is) is set to the TranslationModel property, so the problem is not context related. Setting the binding mode of the column to Two Way did not help either, as it is supposed to by Two Way as default.
I've found many posts relating to the opposite problem : updating the item source not updating the UI, but some how I can't find anything on this one.
Thanks for your help !
I've found the solution, it was never the binding, just the fact that the TranslationEntry
was a struct
:
public struct TranslationEntry
{
public string LangCode { get; set; }
public string LangName { get; set; }
public string Translation { get; set; }
}
It should have been:
public class TranslationEntry
{
public string LangCode { get; set; }
public string LangName { get; set; }
public string Translation { get; set; }
}
@Keithernet, thanks for your help.