Feeds:
Posts
Comments

Archive for February, 2011

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}">
 <Button.CommandParameter>
   <Binding ElementName="txtName" /> // this will pass TextBox object to SaveCommand.
 </Button.CommandParameter>
</Button>

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

ViewModel_Ctor()
{ // 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;
   if(txt.Text.Trim().Equal(string.Empty))
  {
     MessageBox.Show("Blank not allowed");  // this will not update the binding
   } 
   else
   {
     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 »