0

ユーザー コントロールのカスタム 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));

ここで Table は、行と列を格納するために使用されるカスタム データ型です。それは私がそれらを次のように使用するのに役立ちます;

<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"/>

テーブルのデータ型を次のように定義しようとしました。

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" を使用すると壊れます。誰でもこれを達成するのを手伝ってもらえますか?

4

2 に答える 2

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> 
于 2012-11-06T20:40:23.787 に答える
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
{
    ...
}
于 2012-11-06T21:05:01.133 に答える