DotNetGeek
DotNetGeek

Reputation: 165

Textbox Event Handling in ViewModel

I have a situation, where I am validating a textbox for enabling the button. If the textbox is empty the button should be disabled and vice verse. I can handle the code and achieve the solution, if I write the logic in the code behind of the XAML but I feel thats not the correct way and the event should be handled from the viewModel instead of the code behind.

Here is what I have done:
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"); 
    }
}


Code behind

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

I am trying to write following code in the viewModel to achieve the solution but not sure what to write.

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

}

Upvotes: 1

Views: 996

Answers (2)

newb
newb

Reputation: 856

The ViewModel is an acceptable place to add supporting properties for your View that do not effect your model. For example, something along the lines of:

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

From there, you can just bind the Button.IsEnabled property to the DncCanExecute property to get the desired functionality.

Upvotes: 1

greg
greg

Reputation: 1314

If you want to validate a TextBox which would disable the button, i would use a command, something similar to this;

    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
    }

This would ensure that the user is unable to continue, or save to progress as the TextBox should not accept a null or empty value, shown within the DCNoteFormCanExecute() (the DCNotes is property that you have defined within your Viewmodel).

and in the xaml, bind it to the button like so;

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

For validation, you could do something simple like so, using attribute validation, using this reference 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");
        }
    }

and within the xaml, you could create a Resource to highlight the box to notify the user of the textbox not been filled out;

  <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>

I hope this helps, otherwise, here's the link that might help; 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

Upvotes: 3

Related Questions