【问题标题】:WPF MVVM Light - Binding of SelectedItem not changingWPF MVVM Light - SelectedItem 的绑定没有改变
【发布时间】:2011-10-06 01:25:24
【问题描述】:

关于这个领域的帖子很多,但没有一个对我有帮助......这是场景:我有两个“季节”下拉菜单来模拟一个范围。如果您在开始范围内选择一个季节,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 没有更改...无法弄清楚发生了什么并查看了这个这么多不同的方式...

【问题讨论】:

  • This question 听起来与您的相似。你试过那个答案吗?

标签: wpf data-binding mvvm mvvm-light


【解决方案1】:

您是否从AvailableSeasons 集合中获得了SelectedSeason?如果没有,您是否实施了一些特别的措施来比较季节?

例如,假设你有

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

如果SelectedSeason = new Season(); SelectedItem 绑定将不起作用,因为new Season();AvailableSeasons 中不存在。

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2016-05-07
      • 2012-09-30
      • 1970-01-01
      • 1970-01-01
      • 2015-08-06
      • 1970-01-01
      • 2020-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多