我在XAML中有一个组合框,写为
<ComboBox ItemsSource="{Binding Path=Options}"
SelectedItem="{Binding Path=CurrentValue}"/>
"CurrentValue
"在ViewModel类中实现为
private string m_CurrentValue;
public string CurrentValue
{
get { return this.m_CurrentValue; }
set
{
if (m_CurrentValue != value)
{
if (IsValid(value))
{
this.m_CurrentValue = value;
SetData(this.m_CurrentValue);
}
this.SendPropertyChangedEvent(nameof(this.CurrentValue));
}
}
}
在这里,在设置CurrentValue
之前,对某些条件进行验证。我的意图是,如果验证失败,将组合框选择更改为以前的值。这不适用于组合框,但是此方法非常适用于CheckBox控件-下面给出的代码片段。
<CheckBox VerticalAlignment="Center" IsChecked="{Binding Path=CurrentValue}" Width="15" IsEnabled="{Binding Path=IsEnabled}"/>
private bool m_CurrentValue;
public bool CurrentValue
{
get { return this.m_CurrentValue; }
set
{
if (m_CurrentValue != value)
{
if (IsValid(value))
{
this.m_CurrentValue = value;
SetData(this.m_CurrentValue);
}
this.SendPropertyChangedEvent(nameof(this.CurrentValue));
}
}
}
有什么方法可以让ComboBox工作吗?任何替代实现也可以。
有什么方法可以让
ComboBox
工作吗?任何替代实现也可以。
您可以使用这里建议的调度器将backing字段设置为以前的值:
private string m_CurrentValue;
public string CurrentValue
{
get { return this.m_CurrentValue; }
set
{
if (m_CurrentValue != value)
{
string previousValue = m_CurrentValue;
//set the field
this.m_CurrentValue = value;
if (IsValid(value))
{
SetData(this.m_CurrentValue);
this.SendPropertyChangedEvent(nameof(this.CurrentValue));
}
else
{
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
m_CurrentValue = previousValue;
this.OnPropertyChanged(nameof(this.CurrentValue));
}), DispatcherPriority.ApplicationIdle);
}
}
}
}
有关详细信息,请参阅链接。
创建一个用户控件,其中包含一个可处理您的需求的组合框。具有可以跟踪的依赖属性,如果需要更改状态值,则可以设置为在包含的组合框中处理操作。
创建一个内部状态变量,该变量具有当前组合选择的索引。当操作检测到返回以前的状态时,将内部组合框设置为该值。