Binding InputValidation additional data using DependencyProperty

[亡魂溺海] 提交于 2019-12-25 03:14:13

问题


kind of missing here something: I'm using input Validation in a datatemplate (which works) and need to supply additional data to the validation (which doesn't work). Using "hard-coded" values (see comment in code below) works, using the binding doesn't.

The datatemplate is applied to elements (which have a "value", "low_lim" and "high_lim" properties) displayed in an listView (this also works). I think I just can't wrap my head around binding.

May be I just looked to long at this problem. If I'm right this is some kind of "visual-tree" problem with the DP...

Any help appreciated.

    <DataTemplate DataType="{x:Type OptionA}" >
            <TextBox Width="100" Validation.ErrorTemplate="{StaticResource validationErrorTemplate}">
                <TextBox.Text>
                    <Binding Path="value" UpdateSourceTrigger="PropertyChanged">
                        <Binding.ValidationRules>
                            <val:NumberOptionValidator>
                                <val:NumberOptionValidator.validRange>
                                    <val:Range low_lim="{Binding low_lim}" high_lim="{Binding high_lim}"/>
                                    <!--<val:Range low_lim="1" high_lim="2"/>-->
                                </val:NumberOptionValidator.validRange>
                            </val:NumberOptionValidator>
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>
            </TextBox>
    </DataTemplate>

回答1:


I'd suggest you implement IDataErrorInfo on OptionA and not use the validation rule.

According to https://blogs.msdn.microsoft.com/wpfsdk/2007/10/02/data-validation-in-3-5/ in the "When to use Validation Rules vs. IDataErrorInfo" section, for "UI or business-layer validation logic":

Use Validation Rules: The validation logic is detached from the data source, and can be reused between controls.

Use IDataErrorInfo: The validation logic is closer to the source.

Here is some code to get you started.

XAML:

<Window x:Class="WpfApplication33.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication33"
        xmlns:val="clr-namespace:WpfApplication33"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:VM />
    </Window.DataContext>
    <Window.Resources>
        <ControlTemplate x:Key="validationErrorTemplate">
            <StackPanel Orientation="Horizontal">
                <AdornedElementPlaceholder x:Name="textBox"/>
                <TextBlock Text="{Binding [0].ErrorContent}" Foreground="Red"/>
            </StackPanel>
        </ControlTemplate>
        <DataTemplate DataType="{x:Type local:OptionA}">
            <TextBox Width="100"
                     Validation.ErrorTemplate="{StaticResource validationErrorTemplate}"
                     Text="{Binding value, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <ListView ItemsSource="{Binding Items}" />
    </Grid>
</Window>

CS:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;

namespace WpfApplication33
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

    public class VM
    {
        public List<OptionA> Items { get; set; }
        public VM()
        {
            Items = new List<OptionA>() {
                new OptionA() {value=1, low_lim = 0, high_lim = 2 },
                new OptionA() {value=2, low_lim = 3, high_lim = 4 }, // too low
                new OptionA() {value=3, low_lim = 2, high_lim = 5 },
                new OptionA() {value=4, low_lim = 6, high_lim = 9 }, // too low
                new OptionA() {value=5, low_lim = 0, high_lim = 4 }, // too high
            };
        }
    }

    public class OptionA : INotifyPropertyChanged, IDataErrorInfo
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private void OPC(string name) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name)); }

        private int _value, _low_lim, _high_lim;
        public int value { get { return _value; } set { if (_value != value) { _value = value; OPC("value"); } } }
        public int low_lim { get { return _low_lim; } set { if (_low_lim != value) { _low_lim = value; OPC("low_lim"); } } }
        public int high_lim { get { return _high_lim; } set { if (_high_lim != value) { _high_lim = value; OPC("high_lim"); } } }

        #region IDataErrorInfo
        public string Error
        {
            get
            {
                return null;
            }
        }

        public string this[string columnName]
        {
            get
            {
                string err = null;
                if (columnName == "value")
                {
                    if (value < low_lim || value > high_lim)
                        err = string.Format("Value is out of the range of {0} to {1}.", low_lim, high_lim);
                }
                return err;
            }
        }
        #endregion
    }
}

Screenshot:



来源:https://stackoverflow.com/questions/36083103/binding-inputvalidation-additional-data-using-dependencyproperty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!