0

As I am new to wpf i am loosing myself in the webpages about similar topic. I hope somebody could help me explain some basic stuff that I could not manage to understand.

I have a wpf application connected over a websocket to the server. The server returns me every 5 seconds a List. Every new list has nothing to do with the old one. When i get the new list, the old one is not important anymore. The only property of a Player (in the list) that interests me in his ID.

Somehow I need to refresh or update the listbox. I used the observable collection in this way:

private static ObservableCollection<Player> sample;
private static List<Player> sample2 = new List<Player>();
public List<Player> update
{
   set
   {
   sample2 = value;
   sample = new ObservableCollection<Player>((List<Player>) sample2);      
   onPropertyChanged(sample, "ID");
   }
 }


 private void onPropertyChanged(object sender, string propertyName)
 {
   if (this.PropertyChanged != null)
     PropertyChanged(sender, new PropertyChangedEventArgs(propertyName));
 }

When debugging the propertychanged is always null. Im really lost here how to update the listbox.

The xaml of the listbox goes like this:

<DataTemplate x:Key="PlayerTemplate">
  <WrapPanel>
      <Grid >
        <Grid.ColumnDefinitions x:Uid="5">
          <ColumnDefinition  Width="Auto"/>
          <ColumnDefinition  Width="*"/>
          </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
          <RowDefinition Height="50"/>
          </Grid.RowDefinitions>

        <TextBlock VerticalAlignment="Center" Margin="5" Grid.Column="0" Text="{Binding Path=ID}" FontSize="22" FontWeight="Bold"/>                
      </Grid>                                  
    </WrapPanel>
Matija M.
  • 301
  • 5
  • 13

1 Answers1

1

sample doesn't have a property called "ID" because sample is your collection, not your Player instance. Moreover, since you are completely replacing the collection, there is no point using an observable one. Try this:

private ICollection<Player> players = new List<Player>();

public ICollection<Player> Players
{
    get { return this.players; }
    private set
    {
        this.players = value;

        // the collection instance itself has changed (along with the players in it), so we just need to invalidate this property
        this.OnPropertyChanged(this, "Players");
    }
}
Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
  • I still get get that propertyCanged==null when debugging. somehow it doesnt recognize the change, dont know why... – Matija M. Jun 11 '12 at 12:20
  • np. To avoid that problem in the future, you could use [lambda-based property change notifications](http://stackoverflow.com/questions/3191536/how-to-raise-propertychanged-event-without-using-string-name). – Kent Boogaart Jun 11 '12 at 13:49