How to Add Event to A Templated Control?(UWP C#/XAML)

水 知 125 Reputation points
2024-08-14T08:34:20.29+00:00

I've added a Templated Control from Project > Add New Item > Templated Control and I want to add some event to it, here's it's XAML Source code:

    <Style TargetType="local:TagSuggestBox" >
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:TagSuggestBox">
                    <Border
                        Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                        <StackPanel>
                            <TextBlock Text="{TemplateBinding Header}"
                                       Margin="0,0,0,4"/>
                            <RelativePanel>
                                <TextBox x:Name="BackgroundFakeBox"
                                         RelativePanel.AlignLeftWith="InputBox"
                                         RelativePanel.AlignRightWith="InputBox"
                                         RelativePanel.AlignTopWith="InputBox"
                                         RelativePanel.AlignBottomWith="InputBox"
                                         IsReadOnly="True"/>
                                <TextBox x:Name="InputBox"
                                         Text="{TemplateBinding Text}"
                                         AcceptsReturn="True"
                                         TextWrapping="Wrap"
                                         RelativePanel.AlignLeftWithPanel="True"
                                         RelativePanel.AlignRightWithPanel="True"
                                         RelativePanel.AlignTopWithPanel="True"
                                         RelativePanel.AlignBottomWithPanel="True"
                                         Background="Transparent"
                                         BorderBrush="Transparent"
                                         FocusVisualSecondaryBrush="Transparent"
                                         Margin="16"/>
                            </RelativePanel>
                        </StackPanel>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>


And here's its C# source code(I made it a mess since I don't know what to do)

using
using
using
using
using
using
using
using
using
using
using
using
// The Templated Control item template is documented at https://go.microsoft.com/fwlink/?LinkId=234235
namespace
{
    
    {
        //Control name consts
        
        //Non-public structure
        
        //Controls and locks
        
        
        //Non-public properties
        
        
        {
            
            
            //DefaultStyleKey = typeof(TextBlock);
            
            
        }
        
        {
            
        }
        
        {
            //Hide suggestions
        
        
        
        
            
            
            
            
        
            
            
            
            
        /// <summary>
        /// The text content in text edit area
        /// </summary>
        
        {
            
            
        }
        /// <summary>
        /// Header to show what the control is for
        /// </summary>
        
        {
            
            
        }
        
        
        {
            
            
            
            {
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
            }
        }
        
        {
            
        }
        
        {
            
        }
        
        {
            
        }
        
        {
            
        }
        
        {
            
        }
        
        {
            
        }
        
        {
            
        }
        
        {
            
        }
        
        {
            //Update suggestion
            
        }
        
        {
            
        }
        
        {
            
        }
        
        {
            TagSuggestBox target = 
            
            
            
            {
                
            }
        }
        
        {
            //this.Text = "uwu";
        
        
        /// Clear text in inputbox
        /// </summary>
        
        {
            
            {
                
            }
        }
    }
}

I need help adding two kinds of events to the TagSuggestBox. The first is a TextChanged event that is invoked when the text in the InputBox changes, similar to the TextChanged event of a TextBox. However, the event is not currently running when I use my control.

<local:TagSuggestBox
Text="text"
Header="title"
TextEdited="TagSuggestBox_TextEdited"
TextChanged="TagSuggestBox_TextChanged"/>


private

The second event I want to add is when a property of a specific value, such as Text, is equal to a specific value, the event will launch. Is this possible? Thank you for your help!

Universal Windows Platform (UWP)
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,010 questions
0 comments No comments
{count} votes

Accepted answer
  1. Junjie Zhu - MSFT 18,486 Reputation points Microsoft Vendor
    2024-08-15T07:08:11.27+00:00

    Hi @水 知 , Welcome to Microsoft Q&A!

    The first is a TextChanged event that is invoked when the text in the InputBox changes, similar to the TextChanged event of a TextBox.

    This can be implemented by registering events in OnApplyTemplate.

    public event EventHandler<RoutedEventArgs> inputTextChanged;
                
    protected override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        TextBox inputbox = GetTemplateChild("InputBox") as TextBox;
        if (inputbox != null)
        {
            inputbox.TextChanged += (s, e) => inputTextChanged?.Invoke(s, e);
        }
                   
    }
    

    The second event I want to add is when a property of a specific value, such as Text, is equal to a specific value, the event will launch. Is this possible?

    It is not easy to implement in template control, it will be very complicated, it is recommended that you inherit TextBox(public sealed class TagSuggestBox : TextBox) and bind TemplatedParent in InputBox.

    MainPage.xaml

     <Grid>
         <!--<local:TagSuggestBox x:Name="tagbox" TagHeader="Name" TagText="May"  inputTextChanged="TagSuggestBox_inputTextChanged" />-->
         <local:TagSuggestBox x:Name="tagbox" Header="Name" TextChanged="TagSuggestBox_TextChanged" />
     </Grid>
    

    MainPage.xaml.cs

    private void TagSuggestBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (tagbox.Text == "bug")
        {
            //dosomething();
      }
    }
    

    Generic.xaml

    <Style TargetType="local:TagSuggestBox" >
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="TextBox">
                    <Border
                        Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                        <StackPanel>
                            <TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent},  Path=Header}"
                                       Margin="0,0,0,4"/>
                            <RelativePanel>
                                <TextBox x:Name="BackgroundFakeBox"
                                         RelativePanel.AlignLeftWith="InputBox"
                                         RelativePanel.AlignRightWith="InputBox"
                                         RelativePanel.AlignTopWith="InputBox"
                                         RelativePanel.AlignBottomWith="InputBox"
                                         IsReadOnly="True"/>
                                <TextBox x:Name="InputBox"
                                         Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Text}"                                     
                                         AcceptsReturn="True"
                                         TextWrapping="Wrap"
                                         RelativePanel.AlignLeftWithPanel="True"
                                         RelativePanel.AlignRightWithPanel="True"
                                         RelativePanel.AlignTopWithPanel="True"
                                         RelativePanel.AlignBottomWithPanel="True"
                                         Background="Transparent"
                                         BorderBrush="Transparent"
                                         FocusVisualSecondaryBrush="Transparent"
                                         Margin="16"/>
                            </RelativePanel>
                        </StackPanel>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    

    TagSuggestBox.cs

     public sealed class TagSuggestBox : TextBox //Control
     {
         public TagSuggestBox()
         {
             this.DefaultStyleKey = typeof(TagSuggestBox);
         }
         //public string TagHeader
         //{
         //    get { return (string)GetValue(TagHeaderProperty); }
         //    set { SetValue(TagHeaderProperty, value); }
         //}
         //public static readonly DependencyProperty TagHeaderProperty =
         //    DependencyProperty.Register("TagHeader", typeof(string), typeof(TagSuggestBox), new PropertyMetadata(string.Empty));
         //public string TagText
         //{
         //    get { return (string)GetValue(TagTextProperty); }
         //    set { SetValue(TagTextProperty, value); }
         //}
         //public static readonly DependencyProperty TagTextProperty =
         //    DependencyProperty.Register("TagText", typeof(string), typeof(TagSuggestBox), new PropertyMetadata(string.Empty));
         //public event EventHandler<RoutedEventArgs> inputTextChanged;
             
         //protected override void OnApplyTemplate()
         //{
         //    base.OnApplyTemplate();
         //    TextBox inputbox = GetTemplateChild("InputBox") as TextBox;
         //    if (inputbox != null)
         //    {
         //        inputbox.TextChanged += (s, e) => inputTextChanged?.Invoke(s, e);
         //    }
         //}
     }
    

    Thank you.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. 水 知 125 Reputation points
    2024-08-15T07:34:09.81+00:00

    Thanks, It works! You're my SAVIOUR!

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.