依赖属性在设计时有效,但在运行时没有。为什么?

时间:2012-12-06 12:16:03

标签: wpf dependency-properties

我创建了一个显示数字键盘的自定义控件。该控件具有依赖项属性( ButtonWidth ),用于设置数字键盘中所有键的键大小。当属性更改时,枚举所有子按钮并更新其高度和宽度属性。

在设计时,这很好用。我可以更改属性,数字键盘显示会相应更改。

但是在运行时,会创建数字键盘,但不会更新按钮宽度。我添加了一个按钮,在Click事件中设置宽度,这很有效。

public static readonly DependencyProperty ButtonWidthProperty =
     DependencyProperty.Register("ButtonWidth", 
        typeof(int),
        typeof(VirtualKeyboard), 
        new FrameworkPropertyMetadata(40,
            FrameworkPropertyMetadataOptions.AffectsArrange |
            FrameworkPropertyMetadataOptions.AffectsMeasure |
            FrameworkPropertyMetadataOptions.AffectsRender |
            FrameworkPropertyMetadataOptions.AffectsParentMeasure |
            FrameworkPropertyMetadataOptions.AffectsParentArrange,
        OnButtonWidthPropertyChanged, OnCoerceButtonWidthProperty),
        OnValidateButtonWidthProperty);

public int ButtonWidth
{
    get { return (int)GetValue(ButtonWidthProperty); }
    set { SetValue(ButtonWidthProperty, value); }
}

private static void OnButtonWidthPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
    Console.WriteLine("VK width");
    VirtualKeyboard control = source as VirtualKeyboard;
    int newVal = (int)e.NewValue;
    control.UpdateButtons();
}

private static object OnCoerceButtonWidthProperty(DependencyObject sender, object data)
{
    return data;
}

private static bool OnValidateButtonWidthProperty(object data)
{
    return data is int;
}

public VirtualKeyboard()
{
    Console.WriteLine("VK constr");
    InitializeComponent();
}

protected override void OnInitialized(EventArgs e)
{
    base.OnInitialized(e);
    isCaps = true;
    SetKeys();
    UpdateButtons();  // this is where the current ButtonWidth property 
                      // is read and the button width set
}

private void UpdateButtons()
{
    Console.WriteLine("VK bw=" + ButtonWidth);

    foreach (Button button in FindVisualChildren<Button>(this))
    {
        button.Width = button.Height = ButtonWidth;
    }
}

我注意到,如果我还设置按钮的Content属性,这似乎会强制重新布局控件。

我在这里做错了什么?为什么它在设计时工作但在运行时不工作?

1 个答案:

答案 0 :(得分:1)

尝试在自定义控件加载后更新您的按钮的WidthHeight,即在Loaded事件....不在您的OnInitialized ...因为您需要等待应用模板并创建按钮并在可视树中。

相关问题