使用自定义数据类型的自定义DependencyProperty

时间:2012-11-06 20:34:16

标签: wpf xaml dependency-properties

我想为usercontrol创建自定义DependencyProperty

 public Table Grids
    {
        get { return (Table)GetValue(GridsProperty); }
        set { SetValue(GridsProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Grids.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty GridsProperty =
                DependencyProperty.Register("Grids", typeof(Table), 
                typeof(MyViewer), new UIPropertyMetadata(10));

此处表是用于存储行和列的自定义数据类型。列。这将帮助我像使用它们一样;

<my:MyViewer 
    HorizontalAlignment="Left" 
    Margin="66,54,0,0" 
    x:Name="MyViewer1" 
    VerticalAlignment="Top" 
    Height="400" 
    Width="400"
    Grids="10"/>

<my:MyViewer 
    HorizontalAlignment="Left" 
    Margin="66,54,0,0" 
    x:Name="MyViewer1" 
    VerticalAlignment="Top" 
    Height="400" 
    Width="400"
    Grids="10,20"/>

我尝试将Table数据类型定义为;

public class Table 
    {
        public int Rows { get; set; }
        public int Columns { get; set; }

        public Table(int uniform)
        {
            Rows = uniform;
            Columns = uniform;
        }

        public Table(int rows, int columns)
        {
            Rows = rows;
            Columns = columns;
        }
    }

但它不起作用;当我在XAML中使用Grids =“10”时,它会中断。 任何人都可以帮助我实现这个目标吗?

2 个答案:

答案 0 :(得分:3)

您在注册方法中设置的默认值是不是数据类型不匹配?我相信您希望第一个FrameworkPropertyMetadata参数类似于:

new FrameworkPropertyMetadata(new Table())

new FrameworkPropertyMetadata(null)

然后在XAML中,您可以执行以下操作:

<my:MyViewer>
    <my:MyViewer.Grids>
        <Table Rows="10" Column="20"/>
    </my:MyViewer.Grids>
</my:MyViewer> 

答案 1 :(得分:2)

属性元数据中的默认值类型错误。这将导致加载MyViewer类时出现异常。将默认值设置为例如new Table(10)

除此之外,XAML / WPF不会通过调用正确的构造函数自动将字符串"10""10,20"转换为Table类的实例。您必须编写TypeConverter才能执行此转换。

简单的TypeConverter可能如下所示:

public class TableConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        return sourceType == typeof(string);
    }

    public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
    {
        string tableString = value as string;
        if (tableString == null)
        {
            throw new ArgumentNullException();
        }

        string[] numbers = tableString.Split(new char[] { ',' }, 2);
        int rows = int.Parse(numbers[0]);
        int columns = rows;

        if (numbers.Length > 1)
        {
            columns = int.Parse(numbers[1]);
        }

        return new Table { Rows = rows, Columns = columns };
    }
}

TypeConverter将与您的Table类关联,如下所示:

[TypeConverter(typeof(TableConverter))]
public class Table
{
    ...
}
相关问题