Reputation: 4044
I have a datagrid bound to a Players property:
<DataGrid HorizontalAlignment="Left" SelectedItem="{Binding CurrentPlayer}" Height="374" Margin="121,22,0,0" RowHeaderWidth="0" VerticalAlignment="Top" Width="836" ItemsSource="{Binding Players}" AutoGenerateColumns="false" IsReadOnly="True" SelectionMode="Single" IsEnabled="{Binding Editing, Converter={StaticResource InverseBooleanConverter}}" Grid.RowSpan="2" Grid.ColumnSpan="2">
This Players property is defined like this:
public List<Player> Players
{
get { return repository.Players.OrderBy(x => x.Firstname).ToList(); }
}
The repository contains a DBSet from EF.
When I add a player, I use this code:
private void SaveExecute(object parameter)
{
repository.SavePlayer(currentPlayer);
Editing = false;
}
What I'd like to do now is simple: when the new player is created, the datagrid should refresh. It's bound to the Players property, but no setter is ever used and so calling RaisePropertyChange is not possible there.
I'm stuck here. How to correctly bind it so that when the SavePlayer()-method is called, the datagrid would update and so the new player is shown?
The easiest solution I've found is calling RaisePropertyChanged("Players"); in the SaveExecute() method:
private void SaveExecute(object parameter)
{
repository.SavePlayer(currentPlayer);
RaisePropertyChanged("Players");
Editing = false;
}
But... is this allowed or is this something you shouldn't do? Should you only call RaiseProperyChanged in setters of properties of would this be fine too?
Thanks
Upvotes: 0
Views: 871
Reputation: 44038
change the List<Player>
for an ObservableCollection<Player>
. This is a special type of collection that has events to notify when items are added / removed from it. WPF automatically handles these events and updates the UI accordingly.
Then in your Save()
, just Players.Add(newitem);
and you will see the changes reflected in the UI.
Upvotes: 1
Reputation: 19842
To answer your question, it's perfectly legitimate to call RaisePropertyChanged
from your save execute method, or anywhere else you need to let the UI know that something has changed.
Is it the best way to do it? Probably not, personally, I would look into using the MVVM patten. But then again, if it works for you, then there's nothing wrong with it.
Upvotes: 0