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>

1 Answer 1

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");
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I still get get that propertyCanged==null when debugging. somehow it doesnt recognize the change, dont know why...
np. To avoid that problem in the future, you could use lambda-based property change notifications.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.