Skip to main content
 首页 » 编程设计

c#之ViewModel 中的文本框事件处理

2024年02月20日1452php

我有一种情况,我正在验证用于启用按钮的文本框。如果文本框为空,则应禁用该按钮,反之亦然。如果我在 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" />  


View 模型

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(); 
 
} 

请您参考如下方法:

如果你想验证一个会禁用按钮的 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 
    } 

这将确保用户无法继续或保存进度,因为 TextBox 不应接受 null 或空值,如 DCNoteFormCanExecute() 中所示(DCNotes 是您的属性已在您的 Viewmodel 中定义)。

然后在 xaml 中,像这样将它绑定(bind)到按钮;

<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