0

我创建了一个显示数字键盘的自定义控件。该控件有一个依赖属性 ( ButtonWidth ),它设置数字键盘中所有键的键大小。当属性更改时,所有子按钮都会被枚举,并且它们的 Height 和 Width 属性也会更新。

在设计时,这工作正常。我可以更改属性,数字键盘显示也会相应更改。

但是在运行时会创建数字键盘,但不会更新按钮宽度。我添加了一个在 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 属性,这似乎会强制重新布局控件。

我在这里做错了什么?为什么它在设计时有效,但在运行时无效?

4

1 回答 1

1

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

于 2012-12-06T13:30:11.550 回答