WPF MVVM Light - SelectedItem的绑定不变

时间:2011-07-15 10:46:16

标签: wpf data-binding mvvm mvvm-light

这个区域有很多帖子,但没有人帮助我......这就是场景:我有两个“赛季”下降来模拟一个范围。如果您在开始范围1中选择一个季节,则viewmodele会自动将绑定到结束范围的属性设置为同一季节(因此它默认为一年而不是范围。这是XAML的样子(删除了很​​多格式化属性以便于阅读):

<ComboBox ItemsSource="{Binding AvailableSeasons, Mode=OneWay}" 
          SelectedItem="{Binding SelectedBeginRangeSeason, Mode=TwoWay}" 
          ItemTemplate="{DynamicResource SeasonItemShortFormat}" />
<ComboBox ItemsSource="{Binding AvailableSeasons, Mode=OneWay}" 
          SelectedItem="{Binding SelectedEndRangeSeason, Mode=TwoWay}" 
          ItemTemplate="{DynamicResource SeasonItemShortFormat}" />

视图模型中的属性如下所示:

private Season _selectedBeginRangeSeason;
private const string SelectedBeginRangeSeasonPropertyName = "SelectedBeginRangeSeason";
public Season SelectedBeginRangeSeason {
  get { return _selectedBeginRangeSeason; }
  set {
    if (_selectedBeginRangeSeason != value) {
      var oldValue = _selectedBeginRangeSeason;
      _selectedBeginRangeSeason = value;

      RaisePropertyChanged<Season>(SelectedBeginRangeSeasonPropertyName, oldValue, value, true);
    }
  }
}

private Season _selectedEndRangeSeason;
private const string SelectedEndRangeSeasonPropertyName = "SelectedEndRangeSeason";
public Season SelectedEndRangeSeason {
  get { return _selectedEndRangeSeason; }
  set {
    if (_selectedEndRangeSeason != value) {
      Debug.WriteLine("Updating property SelectedEndRangeSeason...");

      var oldValue = _selectedEndRangeSeason;
      _selectedEndRangeSeason = value;

      Debug.WriteLine("Broadcasting PropertyChanged event for property SelectedEndRangeSeason...");
      RaisePropertyChanged<Season>(SelectedEndRangeSeasonPropertyName, oldValue, value, true);
    }
  }
}

private void UpdateSelectedSeasonSelectors() {
  // if the end range isn't selected...
  if (_selectedEndRangeSeason == null) {
    // automatically select the begin for the end range
    SelectedEndRangeSeason = _selectedBeginRangeSeason;
  }
}

我已经验证了end属性是否正在使用调试语句和单元测试进行更改,但是当我选择它时UI不会改变...无法弄清楚发生了什么并且已经看过这个这么多不同的方式......

2 个答案:

答案 0 :(得分:2)

您是否从SelectedSeason收藏中获得了AvailableSeasons?如果没有,你是否实施了一些特殊的比较季节?

例如,假设你有

<ComboBox ItemsSource="{Binding AvailableSeasons}" 
          SelectedItem="{Binding SelectedSeason}" />

如果SelectedSeason = new Season();,SelectedItem绑定将无效,因为new Season();中不存在AvailableSeasons

您需要为SelectedItem设置SelectedSeason = AvailableSeasons[x]才能生效,因为这会使两个项目完全相同。或者您可以实施一些自定义方法来比较两个季节,看看它们是否相同。通常我只是覆盖要比较的类的ToString()方法。

答案 1 :(得分:1)

尝试从ViewModel触发事件以通知UI刷新日历。