2012-06-11 86 views
0

因爲我是wpf的新手,我在關於類似主題的網頁上放棄了自己。我希望有人能幫我解釋一些我無法理解的基本內容。又一個wpf列表框刷新

我有一個通過websocket連接到服務器的wpf應用程序。服務器每5秒返回一個List。每一個新名單都與舊名單無關。當我得到新的列表時,舊的不再重要。玩家(在列表中)唯一對我感興趣的玩家身份。

不知怎的,我需要刷新或更新列表框。我以這種方式使用可觀察的集合:

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)); 
} 

調試時,屬性changed始終爲空。我真的在這裏失去了如何更新列表框。

ListBox的XAML是這樣的:

<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

sample沒有一個叫"ID"屬性,因爲sample是你的收藏,而不是你Player實例。此外,由於您完全取代了收藏品,因此使用可觀察的收藏品沒有意義。試試這個:

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"); 
    } 
} 
+0

在調試的時候我還是得到了那個propertyCanged == null。不知何故,它不承認改變,不知道爲什麼... –

+0

請張貼您的所有XAML和代碼。 –

+0

好的,我拼寫錯誤的東西,現在它的工作,謝謝你:) –