I’m pretty new to WPF, and I’m trying to write a custom control that is basically a TextBlock, but also has a click event. I tried piecing the thing together from various sources, but it does not work.
In the following code, I would expect that OnMouseLeftButtonDown is called when a mouse click is performed on the element. If that happens, I want to raise the Click event. Looking in the debugger, the function is never called.
Did I misunderstand how this is supposed to work, or did some other error find it’s way into my code?
namespace EP3_gui.Controls
{
public class ClickableTextBlock : TextBlock
{
public ClickableTextBlock() : base()
{ }
public ClickableTextBlock( Inline inline )
: base( inline )
{ }
protected override void OnMouseLeftButtonDown( MouseButtonEventArgs e )
{
base.OnMouseLeftButtonDown( e );
RoutedEventArgs args = new RoutedEventArgs( ClickEvent );
RaiseEvent( args );
}
public static readonly RoutedEvent ClickEvent = EventManager.RegisterRoutedEvent(
"Click",
RoutingStrategy.Bubble,
typeof( RoutedEventHandler ),
typeof( ClickableTextBlock )
);
public event RoutedEventHandler Click
{
add { AddHandler( ClickEvent, value ); }
remove { RemoveHandler( ClickEvent, value ); }
}
}
}
As @menty pointed out, there is no error in the code, I made a mistake when testing the Control. In the XAML to test it I entered a value, because otherwise the control would have had no height and width (using Auto for sizes)
My code was
If one changes that to
it works, but then one is not able to see the element in the designer. In my case it was very bad, since the size of the parent user control was set to
auto, so the whole control looked wrong on the designer.The solution is to provide a default value for the binding:
This way it works, and the control is visible in the designer.