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

标签 c# wpf xaml

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

关于c# - ViewModel 中的文本框事件处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14200580/

相关文章:

c# - 在 ServiceStack 中是否可以模拟 Request.OriginalRequest 对象进行单元测试?

c# - 这种重载决议有何意义?

wpf - 如何使覆盖控件高于所有其他控件?

c# - 列表框 IsSynchronizedWithCurrentItem 导致选择第一项,即使没有告诉它这样做

c# - TabControl 中所有 TabItem 的内容相同

c# - F# 2.0 中的错误与泛型类型参数的约束在哪里有关?

c# - 原型(prototype)设计模式与 ICloneable

c# - 创建与标题具有相同属性的标签

c# - 使用 IDataErrorInfo 的 WPF MVVM 验证

wpf - 渐变背景图像