使用 DropDownOpened 刷新 ComboBox 导致丢失选中
Posted
技术标签:
【中文标题】使用 DropDownOpened 刷新 ComboBox 导致丢失选中【英文标题】:Refresh ComboBox with DropDownOpened result in loosing selected 【发布时间】:2021-09-18 18:25:48 【问题描述】:我有一个包含活动网络接口条目的组合框。我喜欢在用户每次打开下拉菜单时刷新条目。
遗憾的是,如果 ComboBox 打开然后关闭(右侧有箭头),则不再显示所选条目。 ComboBox 显示为空。 My ComboBox before and after
如果我删除 DropDownOpened 事件,则在打开关闭 DropDown 后,所选项目将显示在 ComboBox 中。
感谢您的帮助。
这是我的看法:
<ComboBox ItemsSource="Binding HostInterfaces"
SelectedItem="Binding HostInterfaceSelected, Mode=TwoWay"
DisplayMemberPath="Indicator">
<i:Interaction.Triggers>
<i:EventTrigger EventName="DropDownOpened">
<i:InvokeCommandAction Command="Binding Path=DropDownOpenedCommand, Mode=OneWay" />
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
这是我的视图模型:
private RelayCommand _dropDownOpenedCommand;
public ICommand DropDownOpenedCommand => _dropDownOpenedCommand ??
(_dropDownOpenedCommand =
new RelayCommand(ExecuteDropDownOpenedCommand));
private void ExecuteDropDownOpenedCommand(object obj)
HostInterfaces.Clear();
// add several entries
_hostInterfaces.Add( ... );
private readonly ObservableCollection<HostNetworkInterfaceEntry> _hostInterfaces = new ObservableCollection<HostNetworkInterfaceEntry>();
public ObservableCollection<HostNetworkInterfaceEntry> HostInterfaces => _hostInterfaces;
private HostNetworkInterfaceEntry _hostInterfaceSelected;
public HostNetworkInterfaceEntry HostInterfaceSelected
get => _hostInterfaceSelected;
set
if (value == null) return;
if (value == _hostInterfaceSelected) return;
_hostInterfaceSelected = value;
OnPropertyChanged(nameof(HostInterfaceSelected));
我的 HostNetWorkInterfaceEntry 类:
public class HostNetworkInterfaceEntry
public HostNetworkInterfaceEntry(string name, IPAddress address)
Name = name;
Address = address;
public string Name get; private set;
public IPAddress Address get; private set;
public string Indicator => (Address != null ? $"Address Name" : $"Name");
【问题讨论】:
value == _hostInterfaceSelected
do reference equals ...明显的解决方案是提供自己的实现(覆盖object.Equals
和相关)...也有可能SelectedItem
在没有项目时无效...所以您需要在清除本地之前存储并在添加元素后恢复它
您正在清除HostInterfaces.Clear();
,跟踪选择的值并在填充时再次选择正确的项目。
【参考方案1】:
感谢@Senir 和@Jeroen van Langen。您的提示引导我找到解决方案。
我必须修改属性 HostInterfaceSelected 以及 ExecuteDropDownOpenedCommand 方法。
public HostNetworkInterfaceEntry HostInterfaceSelected
get => _hostInterfaceSelected;
set
// removed that -> if (value == null) return;
if (value == _hostInterfaceSelected) return;
_hostInterfaceSelected = value;
OnPropertyChanged(nameof(HostInterfaceSelected));
private void ExecuteDropDownOpenedCommand(object obj)
var saveSelected = HostInterfaceSelected; // added this
HostInterfaces.Clear();
// add several entries
_hostInterfaces.Add( ... );
// restore saved to HostInterfaceSelected
if (saveSelected != null)
HostInterfaceSelected = _hostInterfaces.FirstOrDefault(s => s.Name == saveSelected.Name && s.Address != null && s.Address.Equals(saveSelected.Address));
【讨论】:
以上是关于使用 DropDownOpened 刷新 ComboBox 导致丢失选中的主要内容,如果未能解决你的问题,请参考以下文章