0

我有一个包含以下 XAML 的 UserControl:

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

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

公共静态只读 DependencyProperty DisplayTypeProperty = DependencyProperty.Register("DisplayType", typeof(DisplayTypeEnum), typeof(myUserControl), new PropertyMetadata(default(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)无法识别。我究竟做错了什么?

提前致谢!

4

1 回答 1

2

你可以使用回调

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

我希望它有所帮助,

问候

于 2012-07-26T13:06:31.320 回答