根据自定义DependencyProperty设置控件的可见性

时间:2012-07-26 12:52:06

标签: wpf enums dependency-properties

我有一个UserControl,其中包含以下XAML:

<GroupBox>
    <Grid>
        <Button x:Name="btn" Content="Test"/>
        <TextBlock x:Name="txt" Visibility="Collapsed"/>
    </Grid>
</GroupBox>

我使用以下代码添加了enum类型的DependencyProperty:

  

public static readonly DependencyProperty DisplayTypeProperty =   DependencyProperty.Register(“DisplayType”,typeof(DisplayTypeEnum),   typeof(myUserControl),new   PropertyMetadata(默认(DisplayTypeEnum.Normal)));

    public DisplayTypeEnum DisplayType
    {
        get
        {
            return (DisplayTypeEnum)this.Dispatcher.Invoke(DispatcherPriority.Background, (DispatcherOperationCallback)delegate
            { return GetValue(DisplayTypeProperty); }, DisplayTypeProperty);

        }
        set
        {
            this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate
            { SetValue(DisplayTypeProperty, value); }, value);
        }
    }

现在我希望能够根据我的DependencyProperty设置两个控件的可见性。

我已经尝试添加以下触发器,但我收到3个错误:

<UserControl.Triggers>
<Trigger Property="DisplayType" Value="Text">
            <Setter Property="Visibility" TargetName="btn" Value="Collapsed"/>
            <Setter Property="Visibility" TargetName="txt" Value="Visible"/>
</Trigger>
</UserControl.Triggers>

第一个错误表明无法识别或访问成员“DisplayType”。 另外两个告诉我控件(txt和btn)无法识别。 我做错了什么?

提前致谢!

1 个答案:

答案 0 :(得分:1)

您可以使用callBack

public static readonly DependencyProperty DisplayTypeProperty = DependencyProperty.Register("DisplayType", typeof(DisplayTypeEnum), typeof(myUserControl), new PropertyMetadata(YourDPCallBack));

private static void YourDPCallBack(DependencyObject instance, DependencyPropertyChangedEventArgs args)
{
     YourUserControl control =   (YourUserControl)instance;
     // convert your Display enum to visibility, for example: DisplayType dT = args.NewValue
     // Or do whatever you need here, just remember this method will be executed everytime
     // a value is set to your DP, and the value that has been asigned is: args.NewValue
     // control.btn.Visibility = dT;
     // txt.Visibility = dT;
}

我希望它有所帮助,

此致

相关问题