【问题标题】:ComboBox Validation without Binding没有绑定的组合框验证
【发布时间】:2012-07-28 03:20:50
【问题描述】:

这个问题基于this solution,但我不知何故无法使用组合框来解决这个问题。我想验证单击提交按钮后,组合框有一个选定的项目并且不为空。请注意,我不是故意绑定任何东西,也不是因为我不知道如何绑定。但如果答案是我无法在不绑定的情况下使用验证规则(特别是针对 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"....>

非常感谢您的帮助,谢谢。

【问题讨论】:

    标签: c# wpf validation data-binding combobox


    【解决方案1】:

    您不能将属性绑定到组合框上的 selectedItem 上,然后检查该属性是否为空?

       Public string SelectedComboboxItem { get; set; }
    
    
         <ComboBox DataContext="{StaticResource ChargeAssigneeViewSource}"  SelectedItem="{Binding SelectedComboboxItem}" Name="ChargeAssigneeBox" ItemsSource="{Binding}" Width="85">
    

    【讨论】:

    • 我不想对每个没有绑定的组合框项目继续这样做。而且我不想每次都将它绑定到同一个项目。如果这是不可能的,就这么说吧,否则当它包含这种类型的解决方案时,我无法回答。
    猜你喜欢
    • 2011-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-06
    • 1970-01-01
    • 2013-04-13
    • 1970-01-01
    相关资源
    最近更新 更多