(轉載請註明來源:cnblogs coder-fang)this
建立靜態UI類:spa
static class BaseUI { public static readonly DependencyProperty ShowStatusProperty = DependencyProperty.Register("ShowStatus", typeof(int), typeof(UIElement)); public static T FindParent<T>(DependencyObject i_dp) where T : DependencyObject { DependencyObject dobj = (DependencyObject)VisualTreeHelper.GetParent(i_dp); if (dobj != null) { if (dobj is T) { return (T)dobj; } else { dobj = FindParent<T>(dobj); if (dobj != null && dobj is T) { return (T)dobj; } } } return null; } public static childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++) { DependencyObject child = VisualTreeHelper.GetChild(obj, i); if (child != null && child is childItem) return (childItem)child; else { childItem childOfChild = FindVisualChild<childItem>(child); if (childOfChild != null) return childOfChild; } } return null; } }
2. 使用依賴屬性:code
public class ParamGroupBox:GroupBox { public int ShowStatus { get { return (int)GetValue(BaseUI.ShowStatusProperty); } set { SetValue(BaseUI.ShowStatusProperty, value); UpdateUI(); } } public ParamGroupBox() { ShowStatus = 0; this.DataContextChanged += ParamGroupBox_DataContextChanged; ; } private void ParamGroupBox_DataContextChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e) { UpdateUI(); } public void UpdateUI() { if (ShowStatus == 0) { this.Visibility = Visibility.Visible; this.IsEnabled = true; } else if (ShowStatus == 1) { this.Visibility = Visibility.Visible; this.IsEnabled = false; } else { this.Visibility = Visibility.Hidden; this.IsEnabled = false; } } }