C# ViewModel通知绑定组合框列表已更改
我有一个绑定到静态C# ViewModel通知绑定组合框列表已更改,c#,wpf,xaml,mvvm,C#,Wpf,Xaml,Mvvm,我有一个绑定到静态列表的组合框 我想更改列表中的项目,但组合框不会更新以反映更改 XAML 当您“新建”列表时绑定被破坏,您可以使用observablecollection和clear,然后添加项,而不是创建新实例 还修复了组合框的selecteditem属性的绑定 <ComboBox x:Name="cbo" ItemsSource="{Binding ComboBox_Items}" SelectedItem="{Binding cbo_SelectedIt
列表的组合框
我想更改列表中的项目,但组合框不会更新以反映更改
XAML
当您“新建”列表时绑定被破坏,您可以使用observablecollection和clear,然后添加项,而不是创建新实例
还修复了组合框的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" />
另外,最好删除组合框项目的setter,以防止其被重新创建。当您“新建”列表时,绑定被破坏,您可以使用observablecollection和clear并添加项,而不是创建新项instance@dnr3我用observateCollection
尝试了这个方法,我得到的对象引用没有设置为对象的实例。
在Add()
上。你能调试以检查哪一个是空的吗?@dnr3当我Clear()时
observedcollection它使observedcollection\u cbo\u Items
为空,然后我无法添加到它。但如果我使用列表,它会起作用。虽然它使我的组合框项目有一个垂直滚动条。嗯,很抱歉,我不确定这是怎么发生在你身上的,清除ObservalCollection不应该使它为空。我在我的示例项目中尝试过它,它仍然崩溃。我只是在你的示例上尝试过,修改了selecteditem绑定,它工作正常,复制combobxes并将其替换为我看到的这个,它现在正在示例项目中工作。我将在我的主要项目中快速测试。
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"
};
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");
}
}
<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" />