我的应用程序有一些工作模式,可以从模型和用户的UI更改。 当我启动应用程序时,它显示默认模式正确(从模型更新数据)。但是当我从UI更改所选项目时,它会显示所选项目一段时间,然后取消选择它(从UI更新,然后从模型更新)。 我在两种情况下划分了更新逻辑 首先,从UI更新应调用模型更新。 第二,从模型更新UI不应调用模型更新。 我的错是什么? 见下面的代码
查看
<ComboBox ItemsSource="{Binding AlgorithmCollection}"
SelectedItem="{Binding SelectedAlgorithm, Mode=TwoWay}"
Style="{StaticResource AutoOpenComboBoxStyle}" />
视图模型
private NamedInt _selectedAlgorithm;
private ObservableCollection<NamedInt> _algorithmCollection;
public NamedInt SelectedAlgorithm
{
get { return this._selectedAlgorithm; }
set { Set(() => SelectedAlgorithm, ref this._selectedAlgorithm, value);
if (this._needUpdate && Core.Kernel.Instance.PluginController.ActiveConverter != null &&
this._selectedAlgorithm != null)
{
Core.Kernel.Instance.PluginController.ActiveConverter.SetActiveAlgorithm(this._selectedAlgorithm.Id);
}
}
}
public ObservableCollection<NamedInt> AlgorithmCollection
{
get { return this._algorithmCollection; }
set { Set(() => AlgorithmCollection, ref this._algorithmCollection, value);
}
}
我听模型事件更新ViewModel,当它是必须的时候。在ViewModel的构造函数中
Messenger.Default.Register<SoftwareSettingsUpdateMessage>(this, ReceiveUpdateMessage);
private void ReceiveUpdateMessage(SoftwareSettingsUpdateMessage action)
{
if (action.SettingType.HasFlag(SoftwareSettingsType.Algorithm))
{
RefreshAlgorithms();
}
this._needUpdate = true;
}
private void RefreshAlgorithms()
{
var converter = Core.Kernel.Instance.PluginController.ActiveConverter;
var algorithms = converter?.Algorithms;
if (algorithms != null)
{
AlgorithmCollection = new ObservableCollection<NamedInt>(
algorithms.Select((x, index) => new NamedInt(x, index))
);
var activeId = converter.ActiveAlgorithmId;
if (activeId >= 0 && activeId < AlgorithmCollection.Count)
{
this._needUpdate = false;
SelectedAlgorithm = AlgorithmCollection[activeId];
this._needUpdate = true;
}
else
{
SelectedAlgorithm = null;
}
}
else
{
AlgorithmCollection = new ObservableCollection<NamedInt>();
SelectedAlgorithm = null;
}
IsActive = true;
}