WPF笔记: 使用依赖属性及寻找父子控件

(转载请注明来源:cnblogs coder-fang)

 

创建静态UI类:

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. 使用依赖属性:

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;
            }
        }
    }

 

posted @ 2019-04-15 09:42  Coder_fang  阅读(487)  评论(0编辑  收藏  举报