Validating a Combo-Box Selection

时间:2018-12-03 13:22:23

标签: c# wpf

I have a combo box in the XAML written as

<ComboBox  ItemsSource="{Binding Path=Options}" 
           SelectedItem="{Binding Path=CurrentValue}"/>

And the "CurrentValue" is implemented in the ViewModel class as

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));
        }
    }
}

Here before setting CurrentValue, it is validated for some condition. My intention is to change ComboBox box selection to the previous value if the validation fails. This is not working for combo-boxes, however this method works perfectly for CheckBox controls - code snippet given below.

<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));
        }
    }
} 

Is there any way to make this work for ComboBox? Any alternate implementation is also fine.

2 个答案:

答案 0 :(得分:1)

  

有什么办法可以使ComboBox正常工作吗?任何其他实现也可以。

您可以按照建议的here使用调度程序将后备字段设置为上一个值:

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);
            }
        }
    }
}

请参阅链接以获取更多信息。

答案 1 :(得分:0)

创建一个带有组合框的用户控件,该组合框将处理您的需求。具有可跟踪的依赖项属性,如果需要更改到期状态值,则已设置它们以处理包含的组合框中的操作。

创建一个内部状态变量,该变量具有当前组合选择的索引。当操作检测到返回该先前状态时,请将内部组合框设置为该值。