WPF - FindName Returns null when it should not

后端 未结 8 701
-上瘾入骨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:13

    In my experience, this happens when you add items via code-behind. I've found that you can fool FindName() (or the animation framework) via name scopes. That is, when you create your control, you do

        NameScope.GetNameScope(yourContainer).RegisterName("name of your control", yourControlInstance);
    

    For this to work reliably, though, you must make sure that you unregister the name:

        NameScope.GetNameScope(yourContainer).UnregisterName("name of your control");
    

    Posting this for future reference.

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

    Try to use button.FindResource("popSelectIteration")

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

    ellipseStoryboard.Children.Add(myRectAnimation); containerCanvas.Children.Add(myPath); After you add register the controls like RegisterName("TextBlock1", Var_TextBox); or RegisterName(myRectAnimation.Name,myRectAnimation); RegisterName(myPath.Name,myPath);

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

    Little late to the party (and not actually answer to OP question), but

    when you add elements dynamically, they are not findable by FindName. You need to register them by calling RegisterName.

    Example:

    Button myButton = new Button();
    myButton.Content = generateNumber();
    myButton.Name = "button_" + generateNumber;
    
    RegisterName(myButton.Name, myButton);
    
    Panel.Children.Add(myButton);
    object o = Panel.FindName(myButton.Name);
    

    Maybe someone might find this useful.

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

    Try

    LogicalTreeHelper.FindLogicalNode(button, "popSelectIteration");
    
    0 讨论(0)
  • 2020-12-09 08:20

    I would guess it has to do with the difference between the visual and logical tree. The control is in the logical tree but maybe the template for this control has not been applied yet and therefore FindName won't return anything useful.

    You could try to call ApplyTemplate(); on the container first.

    This would also explain why it returns something sometimes.

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