WPF - FindName Returns null when it should not

后端 未结 8 702
-上瘾入骨i
-上瘾入骨i 2020-12-09 07:48

FindName is broken for me :(

The object I am looking for is there. I have proof.

Here is the scenario:

ToggleButton button = (ToggleButton)s         


        
相关标签:
8条回答
  • 2020-12-09 08:37

    I would suggest to avoid using FindName function, based on my experience, expecially problematic when you try to find something in the DataTemplate applied to some control. Instead , if it possible (based on your software architecture) declare Popup in XAML and refer to it like resource or use Binding to set some Model property to it's reference. Good luck.

    0 讨论(0)
  • 2020-12-09 08:39

    I have meet the same question now, but i use the method like below:

        #region Override - OnApplyTemplate
    
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
    
            this.PART_ListViewLeft      = GetTemplateChild(cPART_ListViewLeft)      as ListView;
            this.PART_ListViewCenter    = GetTemplateChild(cPART_ListViewCenter)    as ListView;
            this.PART_ListViewRight     = GetTemplateChild(cPART_ListViewRight)     as ListView;
    
            this.PART_GridViewLeft      = GetTemplateChild(cPART_GridViewLeft)      as DsxGridView;
            this.PART_GridViewCenter    = GetTemplateChild(cPART_GridViewCenter)    as DsxGridView;
            this.PART_GridViewRight     = GetTemplateChild(cPART_GridViewRight)     as DsxGridView;
            if(this.PART_ListViewLeft!=null)
                this.PART_ListViewLeft      .AlternationCount = this.AlternatingRowBrushes.Count;
            if(this.PART_ListViewCenter!=null)
                this.PART_ListViewCenter    .AlternationCount = this.AlternatingRowBrushes.Count;
            if(this.PART_ListViewRight!=null)
                this.PART_ListViewRight     .AlternationCount = this.AlternatingRowBrushes.Count;
          //  ApplyTempleted = true;
            CreateColumnLayout();
        }
        #endregion
    

    if the Control is dynamic create and of which or whose container the 'Visibility' is set to hide or Collapsed ,then the code "this.PART_ListViewLeft = GetTemplateChild(cPART_ListViewLeft) as ListView;" will return null always, the reason is clearly: the datatemplete has not yet been applied before OnApplyTemplate being called!!!!!!! so your question should be the same one!! good luck!

    0 讨论(0)
提交回复
热议问题