ViewModel中的文本框事件处理

本文关键字:事件处理 文本 ViewModel | 更新日期: 2023-09-27 17:51:03

我有一种情况,我正在验证一个文本框是否启用按钮。如果文本框为空,则应禁用该按钮,反之亦然。如果我在XAML后面的代码中编写逻辑,我可以处理代码并实现解决方案,但我觉得这不是正确的方式,事件应该从viewModel处理,而不是后面的代码。

这是我所做的:
XAML

<TextBox Grid.Row="1" Margin="6,192,264,0" Height="60" VerticalAlignment="Top"
         x:Name="txtDNCNotes" Text="{Binding Path=DNCNotes, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" 
         TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" 
         Visibility="{Binding Path=DNCNoteTxtVisibility}" Grid.Column="1"
         behaviour:TextBoxFilters.IsBoundOnChange="True"
         TextChanged="TextBox_TextChanged" /> 


ViewModel

public string DNCNotes
{
    get { return _dncNotes; }
    set { 
        if (_dncNotes == value) return; 
        _dncNotes = value; 
        OnPropertyChanged("DNCNotes"); 
    }
}


代码后面

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    var ctx = LayoutRoot.DataContext as NextLeadWizardViewModel;
    BindingExpression binding = txtDNCNotes.GetBindingExpression(TextBox.TextProperty).UpdateSource();
    ctx.ShowDoNotContact();
}     

我试图在viewModel中编写以下代码以实现解决方案,但不确定要写什么。

public void ShowDoNotContact()
{
    Binding myBinding = new Binding("DNCNotes");
    //myBinding.Source =  DataContext as NextLeadWizardViewModel;
    myBinding.Source = txtDNCNotes;
    myBinding.Path = new PropertyPath("DNCNotes");
    myBinding.Mode = BindingMode.TwoWay;
    myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
    BindingOperations.SetBinding(txtDNCNotes, TextBox.TextProperty, myBinding);
    if (_dncNotes == null)
        OkCommand.IsEnabled = false;
    else
        OkCommand.IsEnabled = CanEnableOk();
}

ViewModel中的文本框事件处理

如果您想验证将禁用按钮的TextBox,我将使用command,类似于此;

    private ICommand showDCNoteCommand;
    public ICommand ShowDCNoteCommand
    {
        get
        {
            if (this.showDCNoteCommand == null)
            {
                this.showDCNoteCommand = new RelayCommand(this.DCNoteFormExecute, this.DCNoteFormCanExecute);
            }
            return this.showDCNoteCommand;
        }
    }
    private bool DCNoteFormCanExecute()
    {
        return !string.IsNullOrEmpty(DCNotes);
    }
    private void DCNoteFormExecute()
    {
        DCNoteMethod(); //This a method that changed the text
    }

这将确保用户无法继续,或保存到进度作为文本框不应该接受null或空值,显示在DCNoteFormCanExecute() (DCNotes是属性,你已经在你的视图模型中定义)。

,在xaml中,像这样将它绑定到按钮;

<Button Content="Save" Grid.Column="1" Grid.Row="20" x:Name="btnSave" VerticalAlignment="Bottom" Width="75" Command="{Binding ShowDCNoteCommand}"

对于验证,您可以做一些简单的事情,使用属性验证,使用这个引用using System.ComponentModel.DataAnnotations;

    [Required(ErrorMessage = "DCNotes is required")]
    [RegularExpression(@"^[a-zA-Z''-''s]{1,5}$", ErrorMessage = "DCNotes must contain no more then 5 characters")] //You can change the length of the property to meet the DCNotes needs
    public string DCNotes
    {
        get { return _DCNotes; }
        set
        {
            if (_DCNotes == value)
                return;
            _DCNotes = value;
            OnPropertyChanged("DCNotes");
        }
    }

,在xaml中,您可以创建一个Resource来突出显示该框,以通知用户文本框未填写;

  <Style TargetType="{x:Type TextBlock}">
        <Setter Property="Margin"
                Value="4" />
    </Style>
    <Style TargetType="{x:Type TextBox}">
        <Setter Property="Margin"
                Value="4" />
        <Style.Triggers>
            <Trigger Property="Validation.HasError"
                     Value="true">
                <Setter Property="ToolTip"
                        Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
            </Trigger>
        </Style.Triggers>
    </Style>

我希望这有帮助,否则,这里有一个链接可能会有所帮助;http://www.codeproject.com/Articles/97564/Attributes-based-Validation-in-a-WPF-MVVM-Applicat

http://www.codearsenal.net/2012/06/wpf-textbox-validation-idataerrorinfo.html .UOv01G_Za0t

ViewModel是为您的视图添加不影响您的模型的支持属性的可接受的地方。例如:

    public bool DncCanExecute
    {
        get
        {
           return "" != _dncNotes;
        }
    }
    public string DNCNotes
    {
        get { return _dncNotes; }
        set { 
            if (_dncNotes == value) return;
            if (("" == _dncNotes && "" != value) || ("" != _dncNotes && "" == value))
            {
                _dncNotes = value;
                OnPropertyChanged("DncCanExecute");
            }
            else
            {
                _dncNotes = value;
            }
            OnPropertyChanged("DNCNotes");
        }
    }

从这里,您可以将Button.IsEnabled属性绑定到DncCanExecute属性以获得所需的功能。