1

I'm messing around with MVVM and I've hit a bit of a roadblock with binding commands to buttons. I have a few buttons in a View ( = UserControl) that are generated based on a list of objects I have.

My code looks like this:

(MainWindow)

<ItemsControl ItemsSource="{Binding ViewModels}" Margin="12,57,12,12" />

(UserControl)

    <ItemsControl ItemsSource="{Binding AllConnections}" Margin="0,34,0,0">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Button Content="{Binding Password}" Height="23" HorizontalAlignment="Left" Margin="114,12,0,0" Name="button1" VerticalAlignment="Top" Width="75" Command="{Binding Path=ConnectCommand}" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

But ConnectCommand isn't being called and I assume it's because XAML is looking for it in the AllConnections binding, rather than the ViewModels binding where it should. How do I specify this?

Valyrion
  • 2,342
  • 9
  • 29
  • 60

2 Answers2

3

You should use Relative source to specify the ancestor. Something like this:

Command = "{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=ViewModel.CommandToBind}"
ema
  • 5,668
  • 1
  • 25
  • 31
1

You can add your command to Resources and just use {StaticResource yourCommand}. This could significally simplify xaml.


Useful links:
WPF Commands, How to declare Application level commands?
Commands as XAML Resources
MVVM Commanding inside of a datatemplate

Community
  • 1
  • 1
Anatolii Gabuza
  • 6,184
  • 2
  • 36
  • 54