A WPF beginner here transitioning to C# from Qt. I have a custom control with separate XAML and CS files, and this control is later used in MainWindow to interact with users.
The control is a knob / gauge (QDial equivalent). I would like the control to raise an event each time the knob is rotated - enabling the main window to handle the remaining logic. Ideally the event should be raised with an int argument (passing the current value of the knob to the slot function), but for the sake of simplicity lets assume no arguments.
I was inspired by these topics: https://learn.microsoft.com/en-us/answers/questions/35083/events-in-custom-control-in-wpf.html and WPF Custom Controls Construction,Triggers and Events - however what I wrote still doesn't work.
The relevant code is as follows:
Control CS:
public partial class KnobControl
{
public static readonly RoutedEvent valueWasChangedEvent = EventManager.RegisterRoutedEvent("valueWasChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(KnobControl));
public event RoutedEventHandler valueWasChanged
{
add { AddHandler(valueWasChangedEvent, value); }
remove { RemoveHandler(valueWasChangedEvent, value); }
}
void onMouseWheelUp() {
(...)
RoutedEventArgs args = new RoutedEventArgs(valueWasChangedEvent, this);
this.RaiseEvent(args);
}
}
In the MainWindow XAML the control is described as follows:
<local:KnobControl x:Name="KnobBrightness" valueWasChanged="onBrightnessValueChanged" />
And in the MainWindow CS I have - what I believe - is a function which should handle the event:
private void onBrightnessValueChanged(object sender, EventArgs e)
{
Debug.WriteLine("Knob value change event has been registered.");
}
However, the above solution will not compile, with VS throwing the following error:
System.Windows.Markup.XamlParseException: ''Failed to create a 'valueWasChanged' from the text 'onBrightnessValueChanged'.'
Would anyone be able to advise what am I doing wrong?