//初始化数据,默认选中第一项,事件驱动
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;