繁体   English   中英

如何公开属于用户控件的控件的属性(DependencyProperty)

[英]How do you expose a property (DependencyProperty) of a control that is part of a user control

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

谢谢

如果要从按钮派生自定义/用户控件,则可见性属性应直接在xaml中可用,而无需进行任何更改。 但是,如果要创建依赖项属性,则可以采用这种方法

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM