Reputation: 67
I am new to mvvm, I want to pass textbox.text as input to service method, that method should be called in button click. For this I have wrote the below code, but I am unable to retrieve the textbox value. Commands.cs:
private Action<object> _action;
public Commands(Action<object> action)
{
_action = action;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
if (parameter != null)
{
_action(parameter);
}
else
{
_action("Hello World");
}
}
CommentsandRatingViewModel:
private ICommand _submitButtonCommand;
CommentesAndRating model;
private string Comments;
public string _Comments
{
get
{
// return model._Comments;
return Comments;
}
set
{
//model._Comments = value;
Comments = value;
}
}
public string Rating;
#region Methods
//place this command name in the any of view control's commnad
//like under submitbutton click of Submit Button in Comment.xaml
public ICommand SubmitButtonCommand
{
get
{
return _submitButtonCommand;
}
set
{
_submitButtonCommand = value;
}
}
public CommentsandRatingViewModel()
{
// this.model = new CommentesAndRating();
SubmitButtonCommand = new Commands(new Action<object>(SubmitCommentsAndRatings));
}
public void SubmitCommentsAndRatings(object obj)
{
var commnets = _Comments;
MessageBox.Show("hello");
//have to call service method here.
}
xaml:
<Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}">
<TextBox HorizontalAlignment="Left" Name="txt" Text="{Binding Source= {StaticResource viewmodel},Mode=TwoWay,Path=_Comments}" Height="72" Margin="14,96,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="456"/>
<Button Command="{Binding SubmitButtonCommand}" Content="Button" HorizontalAlignment="Left" Margin="119,249,0,0" VerticalAlignment="Top"/>
</Grid>
Upvotes: 0
Views: 2298
Reputation: 2568
Make a TwoWay databinding between the TextBox.Text property and your Comments property so the UI is allowed to push the value down to your ViewModel.
<TextBox Text="{Binding Comments, Mode=TwoWay}"/>
Upvotes: 0
Reputation: 2571
You need to implement the INotifyPropertyChanged interface to make your binding work.
After that you can use the property _Comment
to get the value needed for your service method.
As a side-note: Do not put an underscore in front of your property name. This will confuse a lot of people reading your code. Better is to use the case sensitivity in C#:
private string comments;
public string Comments
{
...
}
But if you really feel the need to use an underscore then use it for your backing field, not your property.
Upvotes: 3