如何公开作为用户控件一部分的控件的属性(DependencyProperty)

时间:2014-12-15 10:47:41

标签: wpf vb.net user-controls

我已经为我正在创建的用户控件添加了几个自定义按钮。在其中一些按钮上,我想向最终用户公开他们的可见性属性,允许他们决定是否希望它们可见。如何做到这一点?

由于

1 个答案:

答案 0 :(得分:1)

如果要从按钮派生自定义/用户控件,则可以直接在xaml中使用Visibility属性而不进行任何更改。但是如果你想创建一个依赖属性,那么你可以遵循这种方法

public bool ShowHide
        {
            get { return (bool)GetValue(ShowHideProperty); }
            set { SetValue(ShowHideProperty, value); }
        }



public static readonly DependencyProperty ShowHideProperty = DependencyProperty.Register("ShowHide", typeof(bool), typeof(MyControl), new PropertyMetadata(true,OnShowHideChanged));

        private static void OnShowHideChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            MyControl c = d as MyControl;
            if(c!=null)
            {
                if((bool)e.NewValue == true)
                {
                    c.Visibility = Visibility.Visible
                }
                else
                {
                    c.Visibility = Visibility.Collapsed;
                }
            }
        }

在你的xaml中你可以做到

<controls:MyControl ShowHide="true" ..../>

编辑VB转换

Public Shared ReadOnly ShowHideProperty As DependencyProperty = DependencyProperty.Register("ShowHide", GetType(Boolean), GetType(MyClass), New FrameworkPropertyMetadata(False, FrameworkPropertyMetadataOptions.AffectsRender, New PropertyChangedCallback(AddressOf onShowHideChanged)))


    Public Property ShowHide() As Boolean
        Get
            Return CBool(GetValue(ShowHideProperty))
        End Get
        Set(ByVal value As Boolean)
            SetValue(ShowHideProperty, value)
        End Set
    End Property

以下是完整的vb代码

Public ReadOnly ShowHideFirstButtonProperty As DependencyProperty = DependencyProperty.Register("ShowHideFirstButton", GetType(Boolean), GetType(DataNavigator), New FrameworkPropertyMetadata(True, FrameworkPropertyMetadataOptions.AffectsRender, New PropertyChangedCallback(AddressOf onShowHideFirstButtonChanged)))


Public Property ShowHideFirstButton As Boolean
    Get
        Return CBool(GetValue(ShowHideFirstButtonProperty))
    End Get
    Set(ByVal value As Boolean)
        SetValue(ShowHideFirstButtonProperty, value)
    End Set
End Property

Private Sub OnShowHideFirstButtonChanged()
    If ShowHideFirstButton Then
        First.Visibility = Windows.Visibility.Visible 'First being the button whose visibility is to be changed
    Else
        First.Visibility = Windows.Visibility.Collapsed
    End If

End Sub