【问题标题】:How to implement own DataType property for UserControl如何为 UserControl 实现自己的 DataType 属性
【发布时间】:2012-02-29 09:41:40
【问题描述】:

我想实现一个通过 XAML 代码获取枚举类型的用户控件。现在的问题是如何实现可以接收 DataType 的属性。到目前为止,我尝试过的如下:

代码背后:

public partial class Test : UserControl, INotifyPropertyChanged
{
       #region DependencyProperty: EnumType
        public Type EnumType
        {
            get
            {
                return (Type)GetValue(EnumTypeProperty);
            }
            set
            {
                SetValue(EnumTypeProperty, value);                
            }
        }

        public static readonly DependencyProperty EnumTypeProperty =
            DependencyProperty.Register("EnumType", typeof(Type), typeof(Test),
            new FrameworkPropertyMetadata());
        #endregion
}

在 XAML 中我尝试了这个:

...

<Grid>
        <local:Test EnumType="{x:Type local:TestEnum}" />
</Grid>

...

TestEnum:

public enum TestEnum
{
    eins,
    zwei,
    drei
}

但这不起作用。似乎从未设置 EnumType 属性。

有没有人知道如何正确地做到这一点?

【问题讨论】:

    标签: wpf user-controls properties


    【解决方案1】:

    是什么让您认为它不起作用?我在上面尝试了您的代码,添加了 PropertyChangedCallback:

        public static readonly DependencyProperty EnumTypeProperty =
            DependencyProperty.Register("EnumType", typeof(Type), typeof(Test),
            new FrameworkPropertyMetadata(MyCallBack));
    
        private static void MyCallBack(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            // See if we reach this point
        }
    

    它似乎按预期调用,根据需要将 Type 值分配给 TestEnum。

    【讨论】:

    • 哦,我明白了 - 我只是在错误的地方寻找物业的变化!非常感谢你们的所有回答 - 再次帮助了我!竖起大拇指!
    【解决方案2】:

    试试

    public static DependencyProperty EnumValueProperty = DependencyProperty.Register("EnumValue", typeof(TestEnum), typeof(Test), new PropertyMetadata(null));
    
        public TestEnum EnumValue
        {
            get { return (TestEnum)GetValue(EnumValueProperty); }
            set { SetValue(EnumValueProperty, value); }
        }
    
    <local:Test EnumValue="eins"/>
    

    我不确定您为什么使用 Type 作为属性类型,只需使用 TestEnum 类型。

    您是否遇到任何构建错误?我经常发现有时 XAML 编辑器中的智能感知会在我再次构建控件之前失败,这可能是一个红鲱鱼。

    编辑

    抱歉,我完全搞错了,我设法让你的代码编译和运行,但是我没有看到 enum 类型是智能感知中的有效类型。

    【讨论】:

    • 大概TestEnum只是一个例子。 EnumType 属性应该可以设置为任何类型。
    • 我的意思是属性的数据类型是“Type”,而不是枚举类型:public Type EnumType
    • @bobsmith833,抱歉,我没有正确阅读问题。
    • 没关系!这是一件有点不寻常的事情,所以我一开始也没有正确解释这个问题......
    猜你喜欢
    • 1970-01-01
    • 2013-08-29
    • 2017-09-08
    • 2012-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    相关资源
    最近更新 更多