【问题标题】:WPF UI not updatingWPF UI 未更新
【发布时间】:2016-03-14 14:35:39
【问题描述】:

我迷路了... 我检查了我能想到的一切..

  1. DataContext 已设置!
  2. DebugOutputWindow 中没有 BindingErrors
  3. INotifyPropertyChanged 已正确实现(因为 Button-Clicks 工作...)
  4. 集合已更新(计数 > 0)

但是我的 ComboBox 中的项目没有显示出来。

这里还有什么问题?

这是我的代码:

private void Refresh(bool isAuto)
{
        List<DatabaseEntry> entries = GetBrokenJobs(isAuto);

        Collection.Clear();
        foreach (string jobName in entries.Select(x => x.Description).ToList())
        {
            Collection.Add(jobName);
        }
}

我正在绑定一个 ComboxBox:

ItemsSource="{Binding Path=Collection, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"

private ObservableCollection<string> _collection = new ObservableCollection<string>();
public ObservableCollection<string> Collection
{
    get {return _collection; }
    set
    {
        _collection = value;
        OnPropertyChanged();//<= Has [CallerMemberName] in constructor ...
    }
}

我像往常一样设置 DataContext ..

this.DataContext = MainViewModel.Instance;

由于我所有的按钮和复选框都可以工作,所以这可能不是原点..

编辑

这里还有一些 Xaml

 <ComboBox x:Name="ComboBox"
                      Grid.Row="1"
                      Margin="10"                          
                      Grid.Column="1" 
                      Width="230"
                      VerticalContentAlignment="Center"
                      HorizontalContentAlignment="Center"
                      IsEnabled="{Binding Path=IsJobSelectorEnabled, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
                      SelectedItem="{Binding Path=SelectedJobItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                      ItemsSource="{Binding Path=Collection, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
            </ComboBox>

【问题讨论】:

  • 请在运行时使用 Snoop 检查您的 DataContext 和 Bindings。并请删除 Mode=TowWay 和 UpdateSourceTrigger - 绑定到 ItemsSource 没有意义
  • 奇怪的是:我有复选框,它们可以工作,同一个视图模型上带有命令的按钮也可以。 DataContext 设置为 100%...
  • 没有 xaml 的一无所知
  • Collection.Add 不会触发 Collection 的 setter。在您完成迭代 for 循环以添加项目后,调用 on property changed for Collection 并查看是否使它们显示。
  • @TravisSapp 集合是一个 ObservableCollection。 Clear 和 Add 已经在触发 CollectionChanged 事件。

标签: c# wpf binding combobox


【解决方案1】:

解决方案很简单。将组合框项目源绑定到 ObservableCollection。

这不是必需的 ItemsSource="{Binding Path=Collection, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"

请这样使用 ItemsSource="{Binding ComboBoxList}" 其中 ComboBoxList 是在数据上下文中定义的可观察集合。

【讨论】:

    【解决方案2】:

    我知道这有点违背 observablecollection 应该做的,但我过去遇到过一个问题,即完全忽略添加到现有 ObservableCollection 的问题。

    如果您尝试替换整个 observablecollection 类似的东西,它可能会强制对其进行更新:

    列出条目 = GetBrokenJobs(isAuto);

    Collection = new ObservableCollection(entries.Select(x => x.Description).ToList());

    【讨论】:

      猜你喜欢
      • 2012-12-09
      • 1970-01-01
      • 2014-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-16
      • 2018-01-04
      相关资源
      最近更新 更多