Aracılığıyla paylaş


BindingExpressionBase.ValidateWithoutUpdate Yöntem

Tanım

özelliği veya ConvertedProposedValueolarak ayarlanmış RawProposedValue ilişkili ValidationStep Binding üzerinde tüm ValidationRule nesneleri çalıştırır. Bu yöntem kaynağı güncelleştirmez.

public:
 bool ValidateWithoutUpdate();
public bool ValidateWithoutUpdate ();
member this.ValidateWithoutUpdate : unit -> bool
Public Function ValidateWithoutUpdate () As Boolean

Döndürülenler

Boolean

true doğrulama kuralları başarılı olursa; aksi takdirde , false.

Örnekler

Aşağıdaki örnek, Açıklamalar bölümünde ele alınan senaryoyu gösterir. Örnek, kullanıcının bir kitaplık öğesi için veri girmesini ve verileri göndermesini sağlar. adlandırılmış callNum için bağlama ile TextBox ilişkili bir ValidationRule vardır. TextBox Odak kaybedildiğinde, örnek öğesini çağırırValidateWithoutUpdate. Kullanıcı gönder düğmesine tıkladığında, örnek değişiklikleri işlemeyi çağırır UpdateSource . Aşağıdaki XAML, uygulama için kullanıcı arabirimini oluşturur.

<StackPanel>
    <StackPanel.Resources>
        <Style TargetType="HeaderedContentControl">
            <Setter Property="Margin" Value="2"/>
            <Setter Property="Focusable" Value="False"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="HeaderedContentControl">
                        <DockPanel LastChildFill="False">
                            <ContentPresenter ContentSource="Header" DockPanel.Dock="Left" 
                              Focusable="False" VerticalAlignment="Center"/>
                            <ContentPresenter ContentSource="Content" Margin="5,0,0,0" 
                              DockPanel.Dock="Right" VerticalAlignment="Center"/>
                        </DockPanel>

                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

</StackPanel.Resources>
    <HeaderedContentControl Header="Title">
        <TextBox Width="150" Text="{Binding Path=Title, Mode=TwoWay}"/>
    </HeaderedContentControl>
    <HeaderedContentControl Header="Due Date">
        <TextBox Width="150" Text="{Binding Path=DueDate, StringFormat=d, Mode=TwoWay}">

        </TextBox>
    </HeaderedContentControl>
    
    <HeaderedContentControl Header="Call Number">
        <TextBox Name="CallNum" Width="150"
                 LostFocus="CallNum_LostFocus"
                 Validation.Error="CallNum_Error">
            <TextBox.Text>
                <Binding xmlns:src="clr-namespace:BindingExpressionBaseValidateWithoutUpdating"
                    Path="CallNumber" Mode="TwoWay"
                    NotifyOnValidationError="True"
                    UpdateSourceTrigger="Explicit">
                    <Binding.ValidationRules>
                        <src:CallNumberRule ValidationStep="ConvertedProposedValue"/>
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>
    </HeaderedContentControl>

    <Button Click="Button_Click">Submit</Button>
    
    <HeaderedContentControl Header="Title">
        <TextBlock Text="{Binding Path=Title, Mode=TwoWay}"/>
    </HeaderedContentControl>
    
    <HeaderedContentControl Header="Due Date">
        <TextBlock Text="{Binding Path=DueDate, StringFormat=d, Mode=TwoWay}"/>
    </HeaderedContentControl>
    
    <HeaderedContentControl Header="Call Number">
        <TextBlock Text="{Binding CallNumber}"/>
    </HeaderedContentControl>

</StackPanel>

Aşağıdaki örnekte kullanıcı arabiriminin mantığı gösterilmektedir.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace BindingExpressionBaseValidateWithoutUpdating
{

    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            // Create an object and set it to the window's DataContext.
            LibraryItem item = new LibraryItem("Enter the title",
                    "Enter the call number",  DateTime.Now + new TimeSpan(14, 0, 0, 0));

            this.DataContext = item;
        }

        // Check whether the call number is valid when the
        // TextBox loses foces.
        private void CallNum_LostFocus(object sender, RoutedEventArgs e)
        {
            BindingExpression be = CallNum.GetBindingExpression(TextBox.TextProperty);

            be.ValidateWithoutUpdate();
        }

        // Show the validation error when one occurs.
        private void CallNum_Error(object sender, ValidationErrorEventArgs e)
        {
            if (e.Action == ValidationErrorEventAction.Added)
            {
                MessageBox.Show(e.Error.ErrorContent.ToString());
            }
        }

        // Update the source data object when the user clicks
        // the submit button.
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            BindingExpression be = CallNum.GetBindingExpression(TextBox.TextProperty);

            be.UpdateSource();
        }
    }
}
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Data


Partial Public Class Window1
    Inherits Window
    Public Sub New()
        InitializeComponent()

        ' Create an object and set it to the window's DataContext.
        Dim item As New LibraryItem("Enter the title", "Enter the call number", DateTime.Now + New TimeSpan(14, 0, 0, 0))

        Me.DataContext = item
    End Sub

    ' Check whether the call number is valid when the
    ' TextBox loses foces.
    Private Sub CallNum_LostFocus(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim be As BindingExpression = CallNum.GetBindingExpression(TextBox.TextProperty)

        be.ValidateWithoutUpdate()
    End Sub


    ' Show the validation error when one occurs.
    Private Sub CallNum_Error(ByVal sender As Object, ByVal e As ValidationErrorEventArgs)
        If e.Action = ValidationErrorEventAction.Added Then
            MessageBox.Show(e.[Error].ErrorContent.ToString())

        End If
    End Sub

    ' Update the source data object when the user clicks
    ' the submit button.
    Private Sub Button_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim be As BindingExpression = CallNum.GetBindingExpression(TextBox.TextProperty)

        be.UpdateSource()
    End Sub
End Class

Aşağıdaki örnekte ve uygulaması için veri nesnesi ValidationRule gösterilmektedir.

using System;
using System.ComponentModel;
using System.Windows.Controls;
using System.Globalization;

namespace BindingExpressionBaseValidateWithoutUpdating
{
    // LibraryItem implements INotifyPropertyChanged so that the 
    // application is notified when a property changes.  It 
    // implements IEditableObject so that pending changes can be discarded.
    // In this example, the application does not discard changes.
    public class LibraryItem : INotifyPropertyChanged, IEditableObject
    {
        struct ItemData
        {
            internal string Title;
            internal string CallNumber;
            internal DateTime DueDate;
        }

        ItemData copyData;
        ItemData currentData;

        public LibraryItem(string title, string callNum, DateTime dueDate)
        {
            Title = title;
            CallNumber = callNum;
            DueDate = dueDate;
        }

        public string Title
        {
            get { return currentData.Title; }
            set
            {
                if (currentData.Title != value)
                {
                    currentData.Title = value;
                    NotifyPropertyChanged("Title");
                }
            }
        }

        public string CallNumber
        {
            get { return currentData.CallNumber; }
            set
            {
                if (currentData.CallNumber != value)
                {
                    currentData.CallNumber = value;
                    NotifyPropertyChanged("CallNumber");
                }
            }
        }

        public DateTime DueDate
        {
            get { return currentData.DueDate; }
            set
            {
                if (value != currentData.DueDate)
                {
                    currentData.DueDate = value;
                    NotifyPropertyChanged("DueDate");
                }
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        protected void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }

        #endregion

        #region IEditableObject Members

        public virtual void BeginEdit()
        {
            copyData = currentData;
        }

        public virtual void CancelEdit()
        {
            currentData = copyData;
            NotifyPropertyChanged("");
        }

        public virtual void EndEdit()
        {
            copyData = new ItemData();
        }

        #endregion

    }

    public class CallNumberRule : ValidationRule
    {
        // A valid call number contains a period (.)
        // and 6 characters after the period.
        public override ValidationResult Validate(object value, 
                                         CultureInfo cultureInfo)
        {
            string callNum = (string)value;

            int dotIndex = callNum.IndexOf(".");
            if (dotIndex == -1 || dotIndex == 0)
            {
                return new ValidationResult(false, 
                    "There must be characters followed by a period (.) in the call number.");
            }

            string substr = callNum.Substring(dotIndex + 1);

            if (substr.Length != 6)
            {
                return new ValidationResult(false, 
                    "The call number must have 6 characters after the period (.).");
            }

            return ValidationResult.ValidResult;
        }
    }
}
Imports System.ComponentModel
Imports System.Windows.Controls
Imports System.Globalization

' LibraryItem implements INotifyPropertyChanged so that the 
' application is notified when a property changes. It 
' implements IEditableObject so that pending changes can be discarded.
' In this example, the application does not discard changes.
Public Class LibraryItem
    Implements INotifyPropertyChanged
    Implements IEditableObject
    Private Structure ItemData
        Friend Title As String
        Friend CallNumber As String
        Friend DueDate As DateTime
    End Structure

    Private copyData As ItemData
    Private currentData As ItemData

    Public Sub New(ByVal title As String, ByVal callNum As String, ByVal dueDate As DateTime)
        Me.Title = title
        Me.CallNumber = callNum
        Me.DueDate = DueDate
    End Sub

    Public Property Title() As String
        Get
            Return currentData.Title
        End Get
        Set(ByVal value As String)
            If currentData.Title <> value Then
                currentData.Title = value
                NotifyPropertyChanged("Title")
            End If
        End Set
    End Property

    Public Property CallNumber() As String
        Get
            Return currentData.CallNumber
        End Get
        Set(ByVal value As String)
            If currentData.CallNumber <> value Then
                currentData.CallNumber = value
                NotifyPropertyChanged("CallNumber")
            End If
        End Set
    End Property

    Public Property DueDate() As DateTime
        Get
            Return currentData.DueDate
        End Get
        Set(ByVal value As DateTime)
            If value <> currentData.DueDate Then
                currentData.DueDate = value
                NotifyPropertyChanged("DueDate")
            End If
        End Set
    End Property

#Region "INotifyPropertyChanged Members"

    Public Event PropertyChanged As PropertyChangedEventHandler _
        Implements INotifyPropertyChanged.PropertyChanged

    Protected Sub NotifyPropertyChanged(ByVal info As [String])
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))
    End Sub

#End Region

#Region "IEditableObject Members"

    Public Overridable Sub BeginEdit() _
        Implements IEditableObject.BeginEdit

        copyData = currentData
    End Sub

    Public Overridable Sub CancelEdit() _
        Implements IEditableObject.CancelEdit

        currentData = copyData

        NotifyPropertyChanged("")
    End Sub

    Public Overridable Sub EndEdit() _
        Implements IEditableObject.EndEdit

        copyData = New ItemData()
    End Sub

#End Region

End Class

Public Class CallNumberRule
    Inherits ValidationRule

    ' A valid call number contains a period (.)
    ' and 6 characters after the period.
    Public Overloads Overrides Function Validate(ByVal value As Object,
                               ByVal cultureInfo As CultureInfo) As ValidationResult

        Dim callNum As String = DirectCast(value, String)

        Dim dotIndex As Integer = callNum.IndexOf(".")

        If dotIndex = -1 OrElse dotIndex = 0 Then
            Return New ValidationResult(False,
                "There must be characters followed by a period (.) in the call number.")
        End If

        Dim substr As String = callNum.Substring(dotIndex + 1)

        If substr.Length <> 6 Then
            Return New ValidationResult(False,
                "The call number must have 6 characters after the period (.).")
        End If

        Return ValidationResult.ValidResult
    End Function
End Class

Açıklamalar

yöntemi, ValidateWithoutUpdate bağlamanın kaynağını güncelleştirmeden bağlama üzerinde doğrulama kuralları çalıştırmanızı sağlar. Bu, kullanıcı girişini doğrulamak ve bir uygulamada farklı zamanlarda kaynağı güncelleştirmek istediğinizde kullanışlıdır.

Örneğin, gönder düğmesi içeren bir veri kaynağını güncelleştirmek için bir formunuz olduğunu varsayalım. Kullanıcı formu göndermeye çalışmadan önce geçersiz bir değer girilirse kullanıcıya geri bildirim sağlamak istiyorsunuz. Bağlamanın UpdateSourceTrigger özelliğini Explicit olarak ayarlayıp odağı kaybettiğinde TextBox çağırarak ValidateWithoutUpdate alanın geçerliliğini de kontrol edebilirsiniz.

Şunlara uygulanır