c# - 将验证规则应用于 ListView 的 ItemsSource 属性

标签 c# .net wpf validation data-binding

我想通过检查 ItemsSource 是否包含空集合来验证 ListView。这是 XAML。

<ListView x:Name="lstvItemsInGroup" 
            <ListView.ItemsSource>
                <Binding Path="ItemsInGroup" Mode="OneWay" UpdateSourceTrigger="PropertyChanged">
                    <Binding.ValidationRules>
                        <local:CollectionNotEmptyValidationRule ErrorMessage="You must select at least one item" />
                    </Binding.ValidationRules>
                </Binding> 
            </ListView.ItemsSource>

        </ListView>

这是 ValidationRule。

public class CollectionNotEmptyValidationRule : ValidationRule
    {
        public string ErrorMessage
        { get; set; }



    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        ValidationResult lResult = null;

        IEnumerable<object> lCollection = (IEnumerable<object>)value;
        if (lCollection == null || lCollection.Count() == 0)
        {
            lResult = new ValidationResult(false, ErrorMessage);
        }
        else
        {
            lResult = new ValidationResult(true, null);
        }

        return lResult;
    }

我在加载用户控件时强制验证

lstvItemsInGroup.GetBindingExpression(ListView.ItemsSourceProperty).UpdateSource();

但是甚至没有调用 ValidationRule,我在第一行有一个断点,什么也没有。

有什么线索吗?

谢谢。

最佳答案

在这里http://msdn.microsoft.com/en-us/library/system.windows.data.bindingexpression.updatesource.aspx据说 UpdateSource 方法仅在绑定(bind)处于 TwoWayOneWayToSource 模式时更新源。因此,尝试在您的绑定(bind)上设置 Mode=TwoWay

关于c# - 将验证规则应用于 ListView 的 ItemsSource 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4728398/

相关文章:

c# - 全局 Windows 按键

c# - 从 XML 数据写入 SQLite 数据库

c# - Nullable<T> 的装箱/拆箱行为如何可能?

c# - UITestException 未标记为可序列化

wpf - 如何确定特定进程是否正在运行 WPF 应用程序?

c# - 使用 Reflector 创建 VisualStudio 项目

c# - 在 Windows 窗体或 WPF 应用程序中使用集成服务项目?

c# - 提高正则表达式的性能

c# - USB 条码扫描器和 WM_KEYDOWN

wpf - 如何让多人处理数据网格中的相同数据