开发者

using viewmodel to control button click

i m trying to control the button_click through the viewmodel(MVVM). I've used following code to create the command

<Button x:Name="GetData" Content="Get Data" Margin="8,8,223,0"   VerticalAlignment="Top">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Click">
            <cmd:EventToCommand Command="GetData_Click"></cmd:EventToCommand>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

the cl开发者_如何学Cicked event should return a list of persons.

Can anyone provide me solution of "How can we create a command in viewmodel?" Please provide answer with a sample code..

Thanx in advance..


If you're using MVVM light you can do something similar to the following:

private RelayCommand _getData_Click = null;
public RelayCommand GetData_Click
{
    get
    {
        return _getData_Click ?? _getData_Click = new RelayCommand(
            () =>
            {
                // Get Person List
            });
    }
}

There is an example of this on MVVM Lights codeplex page

Update You're probably getting the error because you'll need to use DataBinding to setup the command, try

<Button x:Name="GetData" Content="Get Data" Margin="8,8,223,0" VerticalAlignment="Top" Command="{Binding Path=GetData_Click}"/>

or changing your EventToCommand declaration to:

<cmd:EventToCommand Command={Binding GetDataCommand} />

That should work if you've set your ViewModel as the DataContext.


If you have a ViewModel as DataContext behind the view, and you have a command on your ViewModel called GetData_Click then the following is how you do this:

  <Button Command="{Binding Path=GetData_Click"}>

However, I've got a feeling GetData_Click is a function (by the name of it) so on your ViewModel you need to define a command property, e.g.:

  public ICommand GetDataCommand 
  {
       get {  return (_getDataCommand  = _getDataCommand ?? new DelegateCommand(GetData));  }
  } 

where GetData is a function. The simple DelegateCommand implementation can be found here.


In the viewmodel you can write your command (using also MVVM Light Toolkit)

RelayCommand getDataCommand;
public RelayCommand GetDataCommand
{
    get
    {
        if (getDataCommand == null)
        {
            getDataCommand = new RelayCommand(() =>
            {
                //Here comes the command implementation
            });
        }
        return getDataCommand;
    }
}

In the view, change the EventToCommand to this:

<cmd:EventToCommand Command={Binding GetDataCommand} />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜