Using Avalonia Command Parameters to reference an instance of a class

75 Views Asked by At

I am trying to use an avalonia button to call a function that requires an argument with the type of my class "Flashcard". Here's the relevent code,

<SampleControl xmlns:sys="clr-namespace:System;assembly=mscorlib">

<Button.CommandParameter>
    <sys:Flashcard>$self</sys:Flashcard>
</Button.CommandParameter>`

I've tried messing around with the sys:flashcard bit for a while but with only errors cropping up.

1

There are 1 best solutions below

0
B0lver On

The proper way to pass a parameter in a command is to use Bindings. Basically, you have a view - .axaml markup file with code-behind c# class. In this view you can define binding context, either in markup or in code - you can look it up here.

After setting up a binding context to your view model you can create a property with a type you need - in your case it would look like this:

public Flashcard MyFlashcard { get; set; }

And as a final step, you need to bind this property as a command parameter in a markup. You also can create a command and bind it a similar way.

<Button Command={Binding MyCommand} CommandParameter={Binding MyFlashcard}>

As for creating a command, you can read more here.

Hope it helps!

EDIT: In case if you need to bind a visual element as a command parameter, explore this docs section.