Archive for the ‘WPF’ Category

I had scenario where one dependencyproperty is binded to multipe UI elelments so I was not able to update source by simply using Mode=TwoWay property of Binding. I was using MVVM architecture. I need to validate field before updating to source and if field is empty then display message to user and dont set the value of that dependencyproperty.
Here is the solution to access UI textbox in ViewModel by using UpdateSourceTrigger and Binding.CommandParameter.

To get access of control in ViewModel for validation you need to use Binding.CommandParameter property of Button control. see code below:

<TextBox Text="{Binding Path=DisplayName,Mode=TwoWay,UpdateSourceTrigger=Explicit}" />   //DisplayName is also binded to Grid . have defined Explicit so update will not done automatically.
<Button Name="btnSave" Text="Save" Command="{Binding Path=SaveCommand}">
   <Binding ElementName="txtName" /> // this will pass TextBox object to SaveCommand.

So I am done with UI changes now I need to get this TextBox in ViewModel. See ViewModel code below:

{ // constructor of ViewModel
// Command registration process - passing UI object to method
this.SaveCommand = new RelayCommand(param => SaveToDatabase(param), CanSave);

private bool CanSave(object param)
    return true;

public void SaveToDatabase(object param)
if(param != null)
   // cast param to TextBox so you will be able to get Textbox from UI 
  var txt = param as TextBox;
     MessageBox.Show("Blank not allowed");  // this will not update the binding
     txt.GetBindingExpression(TextBox.TextProperty).UpdateSource(); // this will update the source and you will see other   UI element also get updated value
// Now access the property and update database.

I hope this helps to understand UpdateSourceTrigger.Explicit & Button.CommandParameter usage in WPF MVVM architecture.
Comments/Suggestions are always welcome.


Read Full Post »