【问题标题】:ViewModel Notify Bound ComboBox that List has been changedViewModel 通知绑定的 ComboBox List 已更改
【发布时间】:2018-04-29 23:32:16
【问题描述】:

我有一个ComboBox 绑定到静态List

我想更改列表中的项目,但组合框不会更新以反映更改。


XAML

<ComboBox x:Name="cbo" 
          ItemsSource="{Binding ComboBox_Items, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
          SelectedItem="{Binding cbo_SelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
          HorizontalAlignment="Left"
          Margin="0,0,0,0" 
          VerticalAlignment="Top" 
          Width="100" />

C 夏普

ViewModel 类

获取/设置组合框项

public static List<string> _cbo_Items = new List<string>()
{
    "Item 1",
    "Item 2",
    "Item 3"
};

public static List<string> ComboBox_Items
{
    get { return _cbo_Items; }
    set { _cbo_Items = value;}
}

public static string cbo_SelectedItem { get; set; }

另一个类

用新项目更新列表

ViewModel._cbo_Items = new List<string>()
{
    "Item 4",
    "Item 5",
    "Item 6"
};

解决方案

我试过了,它在viewModel.OnPropertyChanged("ComboBox_Items") 上崩溃并出现空异常

public static ViewModel viewModel;

public event PropertyChangedEventHandler PropertyChanged;

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


public static List<string> ComboBox_Items
{
    get { return _cbo_Items; }
    set { _cbo_Items = value;
          viewModel.OnPropertyChanged("ComboBox_Items");
    }
}

【问题讨论】:

  • 当你“新建”列表时绑定被破坏,你可以使用 observablecollection 并清除和添加项目而不是创建新实例
  • @dnr3 我用ObservableCollection pastebin.com/raw/YVSN7Rvz 试过这个,我在Add() 上得到Object reference not set to an instance of an object.
  • 你能调试看看哪个是空的吗?
  • @dnr3 当我 Clear() ObservableCollection 它使 ObservableCollection _cbo_Items 为空时,我无法添加它。但是,如果我使用 List 它可以工作。虽然它使我的 ComboBox 项目有一个垂直滚动条。
  • 嗯,对不起,我不确定你是怎么回事,清除 observablcollection 不应该让它为空。

标签: c# wpf xaml mvvm


【解决方案1】:

当您“新建”列表时绑定被破坏,您可以使用 observablecollection 并清除然后添加项目而不是创建新实例。

还修复了组合框的 selecteditem 属性的绑定

<ComboBox x:Name="cbo" 
      ItemsSource="{Binding ComboBox_Items}"
      SelectedItem="{Binding cbo_SelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
      HorizontalAlignment="Left"
      Margin="0,0,0,0" 
      VerticalAlignment="Top" 
      Width="100" />

而且最好删除 ComboBox_Items 的设置器以防止它被重新创建。

【讨论】:

  • 我在示例项目中尝试过,它仍然崩溃。
  • 我刚刚尝试了您的示例并修改了 selecteditem 绑定,它工作正常,复制并替换组合框 pastebin.com/bWCcVcFw
  • 我明白了,它现在在示例项目中工作。我将在我的主要项目中快速测试。
猜你喜欢
  • 1970-01-01
  • 2010-12-09
  • 2011-06-25
  • 2010-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-24
  • 2012-12-19
相关资源
最近更新 更多