简体   繁体   English

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

[英]Apply Validation Rule to ListView's ItemsSource property

I'd like to validate a ListView by checking if the ItemsSource contains an empty collection. 我想通过检查ItemsSource是否包含空集合来验证ListView。 Here's the XAML. 这是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>

Here's the ValidationRule. 这是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;
    }

I am forcing the validation upon loading the usercontrol with 我在加载usercontrol时强制进行验证

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

But the ValidationRule isn't even called, I have a breakpoint in the first line and nothing. 但是ValidationRule甚至没有调用,我在第一行有一个断点而没有。

Any clues? 有线索吗?

Thank you. 谢谢。

Here http://msdn.microsoft.com/en-us/library/system.windows.data.bindingexpression.updatesource.aspx it is said that the UpdateSource method only updates the source if the binding is in TwoWay or OneWayToSource modes. 这里有http://msdn.microsoft.com/en-us/library/system.windows.data.bindingexpression.updatesource.aspx ,据说如果绑定是在TwoWayOneWayToSource模式下, UpdateSource方法只更新源。 So, try setting Mode=TwoWay on your binding. 因此,尝试在绑定上设置Mode=TwoWay

This works: 这有效:

public class CollectionNotEmptyValidationRule : ValidationRule
{
    public CollectionNotEmptyValidationRule()
        : base(ValidationStep.RawProposedValue, true)
    {
    }

    public string ErrorMessage { get; set; }

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        return (value as IEnumerable<object>)?.Any() == true
            ? ValidationResult.ValidResult
            : new ValidationResult(false, ErrorMessage);
    }
}

<ListView>
    <ListView.ItemsSource>
        <Binding Mode="OneWay"
                    Path="Empty"
                    UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <local:CollectionNotEmptyValidationRule ErrorMessage="Collection cannot be empty" />
            </Binding.ValidationRules>
        </Binding>
    </ListView.ItemsSource>
</ListView>

Doing it like this does not track collection changes. 这样做不会跟踪集合更改。

If you want that you can use: 如果你想要,你可以使用:

public class MinValidationRule : ValidationRule
{
    public static readonly DependencyProperty AssertMinProperty = DependencyProperty.RegisterAttached(
        "AssertMin",
        typeof(int),
        typeof(MinValidationRule),
        new PropertyMetadata(default(int)));

    public MinValidationRule()
        : base(ValidationStep.ConvertedProposedValue, true)
    {
    }

    public string ErrorMessage { get; set; }

    public int Min { get; set; }

    public static void SetAssertMin(DependencyObject element, int value)
    {
        element.SetValue(AssertMinProperty, value);
    }

    public static int GetAssertMin(DependencyObject element)
    {
        return (int)element.GetValue(AssertMinProperty);
    }

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        return ((int)value) >= Min
            ? ValidationResult.ValidResult
            : new ValidationResult(false, ErrorMessage);
    }
}

<ListView MinHeight="20" ItemsSource="{Binding VmItems}">
    <local:MinValidationRule.AssertMin>
        <Binding Path="Items.Count" RelativeSource="{RelativeSource Self}">
            <Binding.ValidationRules>
                <local:MinValidationRule ErrorMessage="Collection must have at least one item" Min="1" />
            </Binding.ValidationRules>
        </Binding>
    </local:MinValidationRule.AssertMin>
</ListView>

如果要验证,则应使用相应的方法,而不是尝试更新源:

BindingExpression.ValidateWithoutUpdate();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ListView ItemsSource属性绑定 - ListView ItemsSource property binding 不断更新ListView的ItemsSource吗? - Update ListView's ItemsSource Constantly? 将ListView的ItemsSource绑定到已绑定属性的属性 - Binding the ItemsSource of a ListView to the property of an already bound property 通过INotifyPropertyChanged更新ListView的ItemsSource - Updating ListView's ItemsSource via INotifyPropertyChanged WPF - ListView 的 ItemsSource 中的绑定不能是列表 - WPF - Binding in ListView's ItemsSource cannot be a List 在不丢失SelectedItem的情况下替换ListView的ItemsSource - Replacing a ListView's ItemsSource Without Loosing SelectedItem 在 Fluent Validation 中,有没有办法从其他验证器的属性规则(例如外键)复制属性的现有规则? - In Fluent Validation, Is there a way for copying existing rule of a property from other validator's property rule for example for foreign keys? 将控件的 ItemsSource 作为值传递给依赖项属性 - Pass a control's ItemsSource as a value to a dependency property UserControl中依赖项属性列表框的ItemsSource - Dependency Property ListBox's ItemsSource in UserControl 在MultiBinding中使用另一个元素的ItemsSource属性 - Use another element's ItemsSource property in a MultiBinding
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM