2012-02-02 82 views
0

編輯:綁定工作正常,如果我從XAML中刪除Minimum="1" ...這可能是一個SL工具包問題?綁定到ObservableCollection.Count不會更新OC更新時

我試圖將從Silverlight Toolkit的NumericUpDown的值綁定到ObservableCollection的Count。

在我的ViewModel的構造函數中,我將項目添加到集合中,並且綁定相應地更新視圖。但是,NumericUpDown中的值不會更改(它保持爲1)。有趣的是,如果我在設計器打開並且IntelliSense運行時編輯綁定,則該值會更新爲正確的值(在設計器中)。

我在這裏做錯了什麼嗎?

綁定代碼

<toolkit:NumericUpDown x:Name="numberOfCubesUpDown" IsEnabled="True" Maximum="9" Minimum="1" Style="{StaticResource ButtonSpinnerHorizontalStyle}" Value="{Binding Path=Cubes.Count}" Height="30" FontSize="14"> 
    <i:Interaction.Triggers> 
    <i:EventTrigger EventName="ValueChanged"> 
     <cmd:EventToCommand Command="{Binding ChangeNumberOfCubesCommand}" PassEventArgsToCommand="True"></cmd:EventToCommand> 
    </i:EventTrigger> 
    </i:Interaction.Triggers> 
</toolkit:NumericUpDown> 

視圖模型綁定定義 CubeSet實現的ObservableCollection

public CubeSet Cubes 
    { 
     get { return _cubes; } 

     set 
     { 
      if (_cubes == value) { return; } 
      _cubes = value; 
     } 
    } 

當我改變CubeSet

 Cubes = new CubeSet(); 
     for (int i = 0; i < 6; i++) { Cubes.Add(new Cube()); } 

回答

0

您的類需要實現INotifyPropertyChanged接口並在setter中引發PropertyChanged事件。

事情是這樣的:

using System.ComponentModel; 

namespace Sample.ViewModels 
{ 
    public class ViewModelBase : INotifyPropertyChanged 
    { 
     #region INotifyPropertyChanged Members 

     public event PropertyChangedEventHandler PropertyChanged; 

     #endregion 

     protected void OnPropertyChanged(string name) 
     { 
      if (PropertyChanged != null) 
      { 
       PropertyChanged(this, new PropertyChangedEventArgs(name)); 
      } 
     } 
    } 
} 

和您的setter /吸氣會是這樣

public CubeSet Cubes 
{ 
    get { return _cubes; } 

    set 
    { 
     if (_cubes == value) { return; } 
     _cubes = value; 

     OnPropertyChanged("Cubes"); 
    } 
} 

如果你希望綁定更新,你應該設置通過setter方法的價值。當然,您可以在課程內的任何位置手動引發OnPropertyChanged事件,並讓View檢查更新後的值。

此外,請務必在綁定上設置模式。我相信默認情況下,它被設置爲OneWay。

編輯:對不起,我忘了它是一個ObservableCollection。也許你有錯誤的DataContext。

+0

我認爲DataContext是正確的,因爲我在設計器中提到IntelliBus時使用的怪癖......但由於某些原因,當ObservableCollection(CubeSet)更新時,PropertyChanged未觸發。 – 2012-02-02 19:04:43

+0

嗯,我會嘗試編寫一個返回收集計數值的getter,並在您添加或從列表中刪除一個項目時手動調用OnPropertyChanged(「Count」)。這意味着你必須重寫ObservableCollection的add/remove/set方法。如果這仍然不起作用,那麼它一定是別的。 – 2012-02-02 23:13:18