Avalonia UI, Bind Button Command in a ListBox to the ViewModel instead of the ItemsSource

883 views Asked by At

I'm messing around with Avalonia UI right now and I'm having trouble implementing an edit button in a list box.

The button should be visible only when the item is selected and should execute an ICommand that is defined in the ViewModel called EditCommand. Visibility binding works just fine, but the Command binding doesn't and I just can't seem to figure out why.

<ListBox Name="ListBoxDisplay" ItemsSource="{Binding ObservableCollection}" SelectedItem="{Binding SelectedItem}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid ColumnDefinitions="2*, *, *">

[snipped listbox content that's not relevant]
                    
                <Button Grid.Column="2" IsVisible="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}, Path=IsSelected}"
                    Command="{Binding ElementName=ListBoxDisplay, Path=DataContext.EditCommand}">
                        Edit
                </Button>
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Already tried a binding it using RelativeSource (either to the ListBox, or the entire UserControl) and binding it directly to the EditCommand.

Error is always the same:

Unable to resolve property or method of name 'EditCommand' on type 'System.Object'. 

Any help would be appreciated!

1

There are 1 answers

1
radoslawik On BEST ANSWER

So the way I used to bind to the ancestor's viewmodel property in those cases was the following:

Command="{Binding $parent[ListBox].DataContext.EditCommand}"

However last time I tried Avalonia 11 I also had similar issues and I found the answer in their documentation - I had to add explicit cast

Command="{Binding $parent[ListBox].((vm:ParentViewModel)DataContext).EditCommand}

Also as a side note, if your button isn't inside another datatemplate you could directly bind to the property IsVisible="{Binding IsSelected}"