OnApplyTemplate not called in Custom Control

前端 未结 6 2048
忘掉有多难
忘掉有多难 2021-02-01 21:47

I have a Custom Control which uses some PART controls:

 [TemplatePart(Name = \"PART_TitleTextBox\", Type = typeof(TextBox))]
    [TemplatePart(Name = \"PART_Titl         


        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-01 22:37

    beside all mentioned above which is correct and you should check for,

    actually OnApplayTemplete() is called but after all property changed calls and I don't know why, it should be called first thing

    so if you are using your PARTs names to get element it will get errors because wpf will not find until OnApplayTemplete() called so, you must add if (your part element != null) condition in front of any code depend on the PARTs names

    then inside OnApplayTemplete() method it self recall all your logical method again and it will work fine

        TextBox textBox;
        public override void OnApplyTemplate()
                {
                    base.OnApplyTemplate();
                    //onther way to get elements & PARTs
                    textBox= Template.FindName("PART_TitleTextBox", this) as TextBox;
    
                    MyMethod();
        
                }
        private void MyMethod()
        {
    if (textBox == null) return;
    //your logical code here
        }
    

提交回复
热议问题