pchajer
pchajer

Reputation: 1584

How to handle enable/disable of button which are in itemtemplate of ListView using MVVM?

I am having ListView control which has button collections inside itemtemplate and want to handle the enable and disable of each button on ViewModel.

Upvotes: 0

Views: 727

Answers (1)

Shimmy Weitzhandler
Shimmy Weitzhandler

Reputation: 104702

My best advice would be: use a command (I usually use Prism's DelegateCommand or DelegateCommand<T>, you can download Prism package via NuGet which makes it literally painless).

You then bind your button's command to the command:

<Button Command="{Binding MyCommand}" />

The CanExecute method of the command will determine if the button is to be enabled or disabled.

Another approach is expose an IsEnabled property in your ItemViewModel, then bind the IsEnabled property on the button to it.

If you need to bind to a property in the parent ViewModel, you could get to it from the template in several approaches.

Here are some:

<UserControl x:Class="MyControl" x:Name="this" ...>

<...>
  <DataTemplate>
    <Grid>
      <Button
        IsEnabled="{Binding DataContext.IsEnabled, ElementName=this}"/>
      <Button
       IsEnabled="{Binding DataContext.IsEnabled, 
 RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MyControl}}}"
    </Grid>
  </DataTemplate>
</...>
</UserControl>

Upvotes: 2

Related Questions