• WPF常用方法,事件驱动和控件遍历


    //初始化数据,默认选中第一项,事件驱动

    RadioButton btn = FuncClass.GetChildObject<RadioButton>(this.stackPanel1, "btnname");
    if (btn != null)
    {
    btn.IsChecked = true;
    btn.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent, btn));
    }

    遍历一类控件或一个控件:

            /// <summary>
            /// 根据控件名找子控件
            /// <para>调用方法:</para>
            /// <para>Button btnMax = FuncClass.GetChildObject(Button)(this, "btnMax");</para>
            /// </summary>
            /// <typeparam name="T">控件类型</typeparam>
            /// <param name="obj">父控件</param>
            /// <param name="name">要找的子控件名称</param>
            /// <returns>返回子控件,若没找到返回 null</returns>
            public static T GetChildObject<T>(System.Windows.DependencyObject obj, string name) where T : System.Windows.FrameworkElement
            {
                System.Windows.DependencyObject child = null;
                T grandChild = null;
    
                for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
                {
                    child = VisualTreeHelper.GetChild(obj, i);
    
                    if (child is T && (((T)child).Name == name | string.IsNullOrEmpty(name)))
                    {
                        return (T)child;
                    }
                    else
                    {
                        grandChild = GetChildObject<T>(child, name);
                        if (grandChild != null)
                            return grandChild;
                    }
                }
                return null;
            }
    
            /// <summary>
            /// 遍历一类控件
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="obj"></param>
            /// <returns></returns>
            public static List<T> GetChildObjects<T>(DependencyObject obj) where T : FrameworkElement
            {
                DependencyObject child = null;
                List<T> childList = new List<T>();
                for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
                {
                    child = VisualTreeHelper.GetChild(obj, i);
                    if (child is T && !string.IsNullOrEmpty(((T)child).Name))
                    {
                        childList.Add((T)child);
                    }
                    childList.AddRange(GetChildObjects<T>(child));
                }
                return childList;
            }

    WPF 窗体居中:
    this.WindowStartupLocation = WindowStartupLocation.CenterScreen;

  • 相关阅读:
    vue 给嵌套的iframe子页面传数据 postMessage
    左边宽度固定,右边宽度自适应的三种写法
    全局变量声明的规范化
    利用__index和__newindex实现默认值表、监控表、只读表
    Metatable和Metamethod
    Lua中的协同程序 coroutine
    Lua中的require
    Lua基础
    D3D的绘制
    效率相关笔记
  • 原文地址:https://www.cnblogs.com/xibei666/p/4397440.html
Copyright © 2020-2023  润新知