0

我正在创建一个自定义控件并创建了一个bindable property. 我想根据这些属性设置孩子。处理这种情况的正确方法是什么?我尝试在我可以连接的基本控件或事件中寻找任何有意义的东西。

例如,我想在Grid设置ColumnCountandRowCount时创建 a 的列/行定义XAML

public class HeatMap: Grid
{
        public HeatMap()
        {
             // Where should I move these?
              Enumerable.Range(1, RowCount)
                .ToList()
                .ForEach(x => RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto }));
              Enumerable.Range(1, ColumnCount)
                  .ToList()
                  .ForEach(x => ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }));
        }


        public static readonly BindableProperty RowCountProperty =
            BindableProperty.Create<HeatMap, int>(p => p.RowCount, 0);

        public int RowCount
        {
            get { return (int)GetValue(RowCountProperty); }
            set { SetValue(RowCountProperty, value); }
        }

        public static readonly BindableProperty ColumnCountProperty =
            BindableProperty.Create<HeatMap, int>(p => p.ColumnCount, 0);

        public int ColumnCount
        {
            get { return (int)GetValue(ColumnCountProperty); }
            set { SetValue(ColumnCountProperty, value); }
        }
 }
4

1 回答 1

1

您的意思是在更新属性时更新列/行吗? BindableProperty.CreatepropertyChanged处理值更新的参数。

public class HeatMap : Grid
{
    public HeatMap()
    {
        // Where should I move these?
        UpdateRows ();
        UpdateColumns ();
    }

    void UpdateColumns ()
    {
        ColumnDefinitions.Clear ();
        Enumerable.Range (1, ColumnCount).ToList ().ForEach (x => ColumnDefinitions.Add (new ColumnDefinition () {
            Width = new GridLength (1, GridUnitType.Star)
        }));
    }

    void UpdateRows ()
    {
        RowDefinitions.Clear ();
        Enumerable.Range (1, RowCount).ToList ().ForEach (x => RowDefinitions.Add (new RowDefinition () {
            Height = GridLength.Auto
        }));
    }

    public static readonly BindableProperty RowCountProperty =
        BindableProperty.Create<HeatMap, int> (p => p.RowCount, 0,
        propertyChanged: (bindable, oldValue, newValue) => ((HeatMap)bindable).UpdateRows ());

    public int RowCount
    {
        get { return (int)GetValue(RowCountProperty); }
        set { SetValue(RowCountProperty, value); }
    }

    public static readonly BindableProperty ColumnCountProperty =
        BindableProperty.Create<HeatMap, int>(p => p.ColumnCount, 0,
        propertyChanged: (bindable, oldValue, newValue) => ((HeatMap)bindable).UpdateColumns ());

    public int ColumnCount
    {
        get { return (int)GetValue(ColumnCountProperty); }
        set { SetValue(ColumnCountProperty, value); }
    }
}
于 2015-06-11T08:46:30.803 回答