没有绑定的ComboBox验证

时间:2012-07-27 17:38:57

标签: c# wpf validation data-binding combobox

这个问题基于this solution,但我不知道怎么能用ComboBox来解决这个问题。我想验证在单击提交按钮时,组合框有一个选定的项目,并且不为空。请注意,我没有故意约束任何事情,而不是因为我不知道如何。但如果答案是我无法在没有绑定的情况下使用验证规则(特别是ComboBoxes,我已通过链接解决方案对文本框进行了处理),请告诉我。

这是我到目前为止所做的:

XAML:

<ComboBox DataContext="{StaticResource ChargeAssigneeViewSource}" Name="ChargeAssigneeBox" ItemsSource="{Binding}" Width="85">
    <ComboBox.SelectedItem>
        <Binding RelativeSource="{RelativeSource Self}" Path="GetType" Mode="TwoWay">
            <Binding.ValidationRules>
                <my:ComboBoxValidationRule ErrorMessage="Please select an Assignee" />
            </Binding.ValidationRules>
        </Binding>
    </ComboBox.SelectedItem>
</ComboBox>

验证规则:

class ComboBoxValidationRule : ValidationRule
{
    private string errorMessage;

    public string ErrorMessage
    {
        get { return errorMessage; }
        set { errorMessage = value; }
    }
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        if (value == null)

            return new ValidationResult(false, ErrorMessage);

        return new ValidationResult(true, null);

    }
}

按钮点击:

private void AddAnHours()
    {
        Employee currEmployee;

        if (!ValidateElement.HasError(ChargeAssigneeBox))
        {
            if (!ValidateElement.HasError(analystTimeTxtBox))
            {
                currEmployee = ChargeAssigneeBox.SelectedItem as Employee;
                item.AddTime(currEmployee, DateTime.Now, double.Parse(analystTimeTxtBox.Text));
                analystTimeTxtBox.Clear();
                ChargeAssigneeBox.SelectedItem = null;
            }
        }

        UpdateTotals();

    }

我得到的错误就在这一行:

currEmployee = ChargeAssigneeBox.SelectedItem as Employee;

但我的ItemsSource正确绑定,所以即使我选择了一个项目,选择项目也不会将其转换为员工对象。我怀疑它与我绑定它有什么关系:

<Binding RelativeSoruce="{RelativeSource Self}" Path="GetType"....>

非常感谢帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

你不能将一个属性绑定到组合框上的selectedItem,然后检查那个属性是否为null?

   Public string SelectedComboboxItem { get; set; }


     <ComboBox DataContext="{StaticResource ChargeAssigneeViewSource}"  SelectedItem="{Binding SelectedComboboxItem}" Name="ChargeAssigneeBox" ItemsSource="{Binding}" Width="85">
相关问题