我有ComboBox
绑定到静态List
。
我想更改列表中的项目,但ComboBox不会更新以反映更改。
<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" />
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");
}
}
答案 0 :(得分: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的setter以防止它被重新创建。