依赖项属性在设计时有效,但在运行时无效.为什么



我创建了一个显示数字键盘的自定义控件。该控件具有依赖项属性 (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 属性,这似乎会强制重新布局控件。

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

尝试在

加载自定义控件后(即在Loaded事件中)更新按钮的WidthHeight。不在初始化中。因为您需要等待应用模板并创建按钮并在可视化树中。

最新更新