ViewModel中的文本框事件处理

时间:2013-01-07 17:03:51

标签: 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" /> 


视图模型

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

}

2 个答案:

答案 0 :(得分:3)

如果您要验证会禁用该按钮的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不应接受空值或空值,显示在DCNoteFormCanExecute()内(您在Viewmodel中定义的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

OR

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

答案 1 :(得分:1)

ViewModel是一个可以为View添加不影响模型的支持属性的可接受位置。例如,类似于:

    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属性以获得所需的功能。

相关问题