简体   繁体   English

在 WPF 中按名称获取 UI 元素(扩展器内部)

[英]Get UI Element (Inside Expander) by name in WPF

For some reasons, I need to generate my UI using dynamic method.由于某些原因,我需要使用动态方法生成我的 UI。 Below is the snippet of my code.下面是我的代码片段。

        string xaml = "";
        UIElement elementM = null;
        xaml = xaml + "<StackPanel Orientation='Vertical'>";

        //Init & FreeSyn
        xaml = xaml + String.Format("<Expander Margin='{0} {1} 0 0' VerticalAlignment='Top'>", iLeftMostPadding, iTopPadding);
        xaml = xaml + "<Expander.Style>";
        xaml = xaml + "<Style TargetType='Expander'>";
        xaml = xaml + "<Setter Property='IsExpanded' Value='True' />";
        xaml = xaml + "<Setter Property='Header' Value='Axes'/>";
        xaml = xaml + "</Style>";
        xaml = xaml + "</Expander.Style>";
        xaml = xaml + "<Border BorderBrush='DodgerBlue' BorderThickness='1'  Margin='3 3 3 0'>";

        xaml = xaml + "<StackPanel Orientation='Vertical'>";
        xaml = xaml + "<StackPanel Orientation='Horizontal'>";
        xaml = xaml + String.Format("<Button Margin='{0} {1} 0 5' Name='btnCheckAll' Background='{2}' Foreground='{3}' Height='25' VerticalAlignment='Bottom' HorizontalAlignment='Right' Width='{4}'>Check All</Button>", iLeftPadding, iTopPadding, szBtnBG, szBtnFG, 82);
        xaml = xaml + String.Format("<Button Margin='{0} {1} 0 5' Name='btnUncheckAll' Background='{2}' Foreground='{3}' Height='25' VerticalAlignment='Bottom' HorizontalAlignment='Right' Width='{4}'>Uncheck All</Button>", iLeftPadding, iTopPadding, szBtnBG, szBtnFG, 82);
        xaml = xaml + "</StackPanel>";

        int nRow = nAxisCount / 4;
        if (nAxisCount % 4 != 0) { nRow++; }

        xaml = xaml + String.Format(" <UniformGrid Columns='4' Rows='{0}'>", nRow);
        for (int i = 0; i < nAxisCount; i++)
        {
            xaml = xaml + String.Format("<CheckBox Height='20' Name='chkIsAxis{0}'  Margin='{1} {2} 0 0' Width='40' IsChecked = 'true'>{0}</CheckBox>", i, 0, iTopPadding);
        }

        xaml = xaml + "</UniformGrid>";
        xaml = xaml + "</StackPanel>";
        xaml = xaml + "</Border>";
        xaml = xaml + "</Expander>";

. .

. .

. .

elementM = (UIElement)XamlReader.Parse(xaml, context);
gridM.Children.Add(elementM);

string szTempM = "";

szTempM = "btnCheckAll";
Button btnCheckAll = CHelper.FindChild<Button>(elementM, szTempM); //Return Null Here !!!
btnCheckAll.Click += btnCheckAll_Click;

I fail to get the button "Check All" & "Uncheck All" by name.我无法按名称获得“全部检查”和“取消全部检查”按钮。 I only success if allocate both button outside the expander.如果在扩展器外分配两个按钮,我只会成功。 Do you know how to get the button by name ?您知道如何按名称获取按钮吗? (Inside expander) (内部扩展器)

I need to add a onClick event into it.我需要在其中添加一个 onClick 事件。

Thank you in advance.先感谢您。

The UI look like this :用户界面如下所示:

在此处输入图片说明

Below is my FindChild code :以下是我的 FindChild 代码:

 public static T FindChild<T>(DependencyObject parent, string childName)
       where T : DependencyObject
    {
        // Confirm parent and childName are valid. 
        if (parent == null) return null;

        T foundChild = null;

        int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < childrenCount; i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);

            // If the child is not of the request child type child
            T childType = child as T;
            if (childType == null)
            {
                // recursively drill down the tree
                foundChild = FindChild<T>(child, childName);

                // If the child is found, break so we do not overwrite the found child. 
                if (foundChild != null) break;
            }
            else if (!string.IsNullOrEmpty(childName))
            {
                var frameworkElement = child as FrameworkElement;
                // If the child's name is set for search
                if (frameworkElement != null && frameworkElement.Name == childName)
                {
                    // if the child's name is of the request name

                    foundChild = (T)child;
                    break;
                }
            }
            else
            {
                // child element found.
                foundChild = (T)child;
                break;
            }
        }

        return foundChild;
    }

Wait until the Button elements that you define in your XAML markup has actually been created before you try to get a reference to the them.等到您在 XAML 标记中定义的 Button 元素实际创建之后,再尝试获取对它们的引用。 You could handle the Loaded event:您可以处理 Loaded 事件:

...
elementM = (UIElement)XamlReader.Parse(xaml);
gridM.Children.Add(elementM);

FrameworkElement fe = elementM as FrameworkElement;
if (fe != null)
{
    fe.Loaded += (s, e) => 
    {
        string szTempM = "btnCheckAll";
        Button btnCheckAll = CHelper.FindChild<Button>(fe, szTempM);
        btnCheckAll.Click += btnCheckAll_Click;
    };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM