【问题标题】:WPF Design-time propertyWPF 设计时属性
【发布时间】:2019-01-18 05:18:37
【问题描述】:

我已经构建了一个用户控件,它基本上是一个网格,可以在每一端都有圆角,也可以是某个多边形。我有一个 Rounded 属性,它可以更改圆角边框和要匹配的多边形的可见性(如果有人设置 Rounded="True",那么圆角边框是可见的并且多边形是隐藏的,反之亦然。

就像在这个问题中一样: UserControl Dependency Property design time

...它在运行时工作得很好,但我似乎无法让它反映设计时的变化。但是,重新启动 VS、清理解决方案、重建、更改构建目标等 - 这些步骤似乎都没有影响。 我的课很基础:

public partial class MyBox : UserControl
{
    public MyBox()
    {
        InitializeComponent();
    }

    public bool Rounded
    {
        get { return (bool)GetValue(RoundedProperty); }
        set
        {
            SetValue(RoundedProperty, value);
            this.edgeRounded.Visibility = (value ? Visibility.Visible : Visibility.Hidden);
            this.edgePolygon.Visibility = (value ? Visibility.Hidden : Visibility.Visible);
        }
    }

    public static readonly DependencyProperty RoundedProperty = DependencyProperty.Register("Rounded", typeof(bool), typeof(MyBox), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender));
}

有什么想法吗?

【问题讨论】:

  • 我通过添加更改的事件处理程序然后更改依赖属性注册以引用它来实现此功能: public static readonly DependencyProperty RoundedProperty = DependencyProperty.Register("Rounded", typeof(bool), typeof (MyBox), new PropertyMetadata(false, RoundedChanged));

标签: c# wpf


【解决方案1】:

我通过添加更改的事件处理程序然后更改依赖属性注册以引用它来实现此功能。我的工作代码:

public partial class MyBox : UserControl
{
    public MyBox()
    {
        InitializeComponent();
    }

    public bool Rounded
    {
        get { return (bool)GetValue(RoundedProperty); }
        set { SetValue(RoundedProperty, value); }
    }

    public static readonly DependencyProperty RoundedProperty = DependencyProperty.Register("Rounded", typeof(bool), typeof(MyBox), new PropertyMetadata(false, RoundedChanged));

    private static void RoundedChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        bool value = (bool)e.NewValue;
        MyBox thisMyBox = (MyBox)sender;

        // Hide/show the edges
        thisMyBox.edgeRounded.Visibility = (value ? Visibility.Visible : Visibility.Hidden);
        thisMyBox.edgePolygon.Visibility = (value ? Visibility.Hidden : Visibility.Visible);
    }
}

【讨论】:

    【解决方案2】:

    也许使用 XAML 将可见性属性绑定到数据上下文视图模型。 我已经用各种方法做到了这一点。

    【讨论】:

    • 目标是拥有设计时属性,所以我可以拥有: 并根据设计属性查看边缘变化。
    • 上面的模型可以继承 INotifyPropertyChanged 以及 UserControl,这样你就可以实现 propertychanged 事件而不是依赖属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 2011-08-10
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 2022-10-20
    相关资源
    最近更新 更多