预定义的UserControl或控件大小

时间:2013-10-22 19:21:44

标签: c# wpf user-controls wpf-controls

我正在尝试实现具有预定义大小(宽度和高度)的控件或用户控件。

我有一个定义大小的枚举:

public enum ControlSizes
{
    // Width x Height
    ControlSizeA, // 310 x 220
    ControlSizeB, // 310 x 450
    ControlSizeC // 310 x 680
}

然后在我的控制中,我定义了一个DependencyProperty和一个允许Size规范的回调方法:

    public static readonly DependencyProperty ControlSizeProperty = DependencyProperty.Register
        ("ControlSize", 
        typeof(ControlSizes), 
        typeof(CustomControl), 
        new PropertyMetadata(ControlSizes.ControlSizeA, OnControlSizePropertyChanged));

public ControlSizes ControlSize
{
    get { return (ControlSize)GetValue(ControlSizeProperty); }
    set { SetValue(ControlSizeProperty, value); }
}

private static void OnControlSizePropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
    CustomControl customControl = source as CustomControl;
    Size controlSize = ControlSizeConverter.ConvertToSize(customControl.ControlSize);
    customControl.Width = controlSize.Width;
    customControl.Height = controlSize.Height;
}

主要思想是拥有预定义的尺寸,并且在设计时可以选择一种尺寸,在可用尺寸下放置控件。

问题是没有正确保存或分配宽度和高度。

有什么想法吗?

提前致谢。

1 个答案:

答案 0 :(得分:0)

假设ControlSizeConverter.ConvertToSize获得ControlSizes个对象并返回Size,并且您希望CustomControlControlSize DP更改时调整其大小,我认为你的回调应该是这样的:

private static void OnControlSizePropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
    CustomControl customControl = source as CustomControl;
    Size controlSize = ControlSizeConverter.ConvertToSize(ControlSize);
    customControl.Width = controlSize.Width;
    customControl.Height = controlSize.Height;
}