【问题标题】:Set Visibility of control based on custom DependencyProperty根据自定义 DependencyProperty 设置控件的可见性
【发布时间】:2012-07-25 01:33:51
【问题描述】:

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

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

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

public static readonly DependencyProperty DisplayTypeProperty = DependencyProperty.Register("DisplayType", typeof(DisplayTypeEnum), 类型(myUserControl),新 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)无法识别。 我做错了什么?

提前致谢!

【问题讨论】:

  • 嗨,也许你可以改变你的方法并在 DependencyProperty 回调中这样做

标签: wpf enums dependency-properties


【解决方案1】:

你可以使用回调

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

希望对你有帮助

问候

【讨论】:

  • 像魅力一样工作!非常感谢!
猜你喜欢
  • 1970-01-01
  • 2011-01-18
  • 1970-01-01
  • 1970-01-01
  • 2013-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多