Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

c# - How do you bind a Button Command to a member method?

I have a ListView in my MVVM WPF implementation, it has a DataTemplate with a button inside. The ListView is bound to a collection of complex objects in the ViewModel.

 <ListView ItemsSource="{Binding Path=ComplexObjects}"
          SelectedItem="{Binding Path=SelectedObject}"
          Width="Auto">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="My Property">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <StackPanel Margin="6,2,6,2">
                            <TextBlock Text="{Binding MyProperty}"/>
                        </StackPanel>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
    </GridViewColumn>
            <GridViewColumn Header="First Name">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <StackPanel Margin="6,2,6,2">
                            <Button Command="{Binding ???}"/>
                        </StackPanel>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
    </GridView>
</ListView.View>

All the text fields are bound with no problem, but can I bind the Button Command to a member method of the ComplexObject? If so is there any way to pass parameters?

I have a feeling I'm probably just evading using an ICommand.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could bind an ICommand on the ViewModel, passing the instance to invoke the method on as a parameter. The ViewModel can then call the appropriate method on the right ComplexObject.

For example:

<DataTemplate>
    <StackPanel Margin="6,2,6,2">
        <Button Command="{Binding DoSomethingCommand, RelativeSource={RelativeSource AncestorType={x:Type ViewModelType}, Mode=FindAncestor}" CommandParameter="{Binding}"/>
    </StackPanel>
</DataTemplate>

Then the viewmodel could look like so:

public ICommand DoSomethingCommand
{
    get { return new DelegateCommand<object>(DoSomething); }
}

private void DoSomething(object instance)
{
    var complexObject = instance as ComplexObject;
    if (complexObject != null)
        complexObject.SomeMethod();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...