0
 <Style TargetType="{x:Type local:CustomControl}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:CustomControl}">
                    <Border BorderThickness="{TemplateBinding BorderThickness}"
                            Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            CornerRadius="1">
                        <Grid>
                            <TextBox x:Name="txtHour" Grid.Column="6" Text="00" Background="{TemplateBinding OpacityMask}" PreviewTextInput ="TextBox_PreviewTextInput"/>
                        </Grid>

                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

I can't handle event PreviewTextInput in code behind. Error 'ResourceDictionary' root element requires a x:Class attribute to support event handlers in the XAML file. Either remove the event handler for the PreviewTextInput event, or add a x:Class attribute to the root element.

  
    public class CustomControl: Control
    {
        static CustomControl()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl), new FrameworkPropertyMetadata(typeof(CustomControl)));
        }
       

        private  void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            MessageBox.Show("TEST");
        }
    }

This is my code behind.

  • Do not confuse the code behind of your control with that of a ResourceDictionary. – Clemens Jul 16 '21 at 11:10
  • Besides that, it may be easier to author a UserControl instead of a custom Control. In the UserControl's XAML you could easily attach event handlers that would be declared in its code behind. – Clemens Jul 16 '21 at 11:13

0 Answers0