views:

404

answers:

3

I did some googling and didn't find an answer to this puzzle.

Provided you have the following:

  • MySuperView
  • MySuperViewModel

MySuperView has two textboxes both bound to string properties on the ViewModel and your using a DelegateCommand to bind your 'Save' button to the ViewModel using syntax such as:

ViewModel:

this.SaveOrderCommand = new DelegateCommand<object>(this.Save, this.CanSave);

View:

Command="{Binding SaveOrderCommand}"

How do you deal with UI Elements to make the User Interaction more pleasing. For example, lets say some lower level failure occurring during the save action of the DelegateCommand and you would like to trigger the tooltip of one of the TextBoxs. How would this typically occur?

I'd like to stick with as clean code-behind as possible but I am not adverse to putting UI specific code in there.

A: 

Basically, you would want a create properties for your view to observe (usually through triggers) that would update your UI depending on what is happening in your code execution.

Chris Nicol
+1  A: 

To show exceptions in a tooltip, I would add a property to the ViewModel that exposes the error message as a string, and bind that to your TextBox's ToolTip. Then in your Save method, you would start by setting that property to the empty string, and then doing all the real work inside a try..catch that, if an exception occurs, pushes the exception message into that property, so it automatically shows up in the ToolTip.

You would need to provide change notification for your property, either by making it a DependencyProperty or by using INotifyPropertyChanged.

Joe White
+6  A: 

I would recommend that your ViewModel implement IDataErrorInfo so you can take advantage of validation stuff in WPF. You don't need to wait until someone clicks the save button, once the textbox gets updated it will be validated.

public string this[ColumnName]
{
  if (Column == "TextProperty")
  {
    if(!ValidateTextProperty())
      return "TextProperty is invalid";
  }
}

void Save(object param)
{
  if (CanSave)
  {
     if (string.IsNullOrEmpty(this["TextProperty"])
     {
        //Add Save code here
     }
  }
}

In your View:

    <TextBox Text={Binding TextProperty, ValidateOnDataErrors="true",
 UpdateSourceTrigger=PropertyChanged}/>

This will put a red box around the textbox and you can add a validation error template to the textbox style to add a tooltip see here

Jose