2

I'm trying to create a very simple application with a canvas that will register a PointerPressed event when the canvas is clicked but I'm getting the following error:

System.Xaml.XamlException: 'Unable to find suitable setter or adder for property PointerPressed of type Avalonia.Input:Avalonia.Input.InputElement for argument System.Private.CoreLib:System.String, available setter parameter lists are: System.EventHandler`1[[Avalonia.Input.PointerPressedEventArgs, Avalonia.Input, Version=0.10.18.0, Culture=neutral, PublicKeyToken=c8d484a7012f9a8b]] Line 8, position 11.' Line number '8' and line position '11'.

XAML:

<Window xmlns="https://github.com/avaloniaui"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
        x:Class="TestCanvas.MainWindow"
        Title="TestCanvas">
  <Canvas PointerPressed="AddShape"/>
</Window>

Code:

using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;

namespace TestCanvas
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public void AddShape(object sender, PointerPressedEventArgs e)
        {

        }
    }
}

I've tried something similar with a button click event as well but get the same kind of error. Am I doing this wrong or is something setup incorrectly in the project that could be causing a problem? I just used the Avalonia Application template.

Turkeyplague
  • 67
  • 1
  • 5

1 Answers1

0

This error is due to the fact that when binding an event handler in XAML, you must use the {x:EventHandler} syntax instead of directly referencing the event handler name.

Therefore, you should update the PointerPressed property in your XAML:

<Canvas PointerPressed="{x:EventHandler AddShape}">
</Canvas>

This will tell XAML to call the AddShape method when the PointerPressed event is fired for that element.

wenbingeng-MSFT
  • 1,546
  • 1
  • 1
  • 8
  • The OP was saying it's an Avalonia Error, are you sure you answer is for Avalonia and not WPF? If it is for Avalonia, how does your method have to look? Does it need sender? – Raid May 20 '23 at 22:29