2012-12-15 29 views
1

我有一個gridview:綁定到在視窗中的ObservableCollection改變物體8的GridView

 <GridView xmlns:controls="using:Windows.UI.Xaml.Controls"> 
     <GridView.ItemTemplate> 
      <DataTemplate> 
       <Grid> 
        <Image Source="{Binding Image}"></Image> 
        <Grid Height="50" Width="50" Background="{Binding Color}"></Grid> 
        <TextBlock FontSize="25" TextWrapping="Wrap" Text="{Binding Name}" Margin="10,10,0,0"/> 
       </Grid> 
      </DataTemplate> 
     </GridView.ItemTemplate> 
    </GridView> 

這個綁定到的ObservableCollection:

ObservableCollection<KeyItem> Keys = new ObservableCollection<KeyItem>(); 

    Keys.Add(new KeyItem { Name = "jfkdjkfd" }); 
    Keys.Add(new KeyItem { Name = "jfkdjkfd" }); 

    myView.ItemsSource = Keys; 

的keyitem是這樣的:

​​

如果我在將其分配給itemssource之前設置顏色,此工作正常。

但我也希望能夠通過編程方式改變KeyItem的顏色屬性後,它被分配,並有綁定改變顏色。但是在這個配置中這不起作用。

什麼是最好的方法來得到這個工作?

回答

5

您的班級需要實施INotifyPropertyChanged。這允許綁定知道何時更新。擁有可觀察集合只會通知綁定到集合以獲得通知。集合中的每個對象也需要執行INotifyPropertyChanged

請注意在NotifyPropertyChanged中使用[CallerMemberName]。這允許具有默認值的可選參數將其作爲其調用成員的名稱。

public class KeyItem : INotifyPropertyChanged 
{ 
    private string name; 
    public string Name 
    { 
     get 
     { 
      return name; 
     } 
     set 
     { 
      name = value; 
      NotifyPropertyChanged(); 
     } 
    } 

    private ImageSource image; 
    public ImageSource Image 
    { 
     get 
     { 
      return image; 
     } 
     set 
     { 
      image = value; 
      NotifyPropertyChanged(); 
     } 
    } 

    private Brush color; 
    public Brush Color 
    { 
     get 
     { 
      return color; 
     } 
     set 
     { 
      color = value; 
      NotifyPropertyChanged(); 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 

    // This method is called by the Set accessor of each property. 
    // The CallerMemberName attribute that is applied to the optional propertyName 
    // parameter causes the property name of the caller to be substituted as an argument. 
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 
} 
+0

不錯的工作人員...... –

相關問題