覆盖 Numberbox 清除按钮 WINUI3 的默认行为

问题描述 投票:0回答:1

我想覆盖 WINU3 NumberBox 清除按钮的默认行为,默认行为将值重置为“0”,但在我的用例中,如果我可以在单击清除按钮时绑定特定命令,那就更好了。 例如,当我点击按钮时,它会将值重置为“5”或另一个默认值。

c# mvvm winui-3 winui winui-xaml
1个回答
0
投票

您可以创建派生自

NumberBox
的自定义控件:

public class NumberBoxEx : NumberBox
{
    public static readonly DependencyProperty DefaultValueProperty =
        DependencyProperty.Register(
            nameof(DefaultValue),
            typeof(double),
            typeof(NumberBoxEx),
            new PropertyMetadata(default));

    public NumberBoxEx() : base()
    {
        Loaded += NumberBoxEx_Loaded;
        Unloaded += NumberBoxEx_Unloaded;
    }

    public Button? DeleteButton { get; private set; }

    public double DefaultValue
    {
        get => (double)GetValue(DefaultValueProperty);
        set => SetValue(DefaultValueProperty, value);
    }

    private void NumberBoxEx_Loaded(object sender, RoutedEventArgs e)
    {
        if (this.FindDescendant<Button>(x => x.Name == nameof(DeleteButton)) is not Button deleteButton)
        {
            return;
        }

        DeleteButton = deleteButton;
        deleteButton.Click += DeleteButton_Click;
    }

    private void NumberBoxEx_Unloaded(object sender, RoutedEventArgs e)
    {
        if (DeleteButton is null)
        {
            return;
        }

        DeleteButton.Click -= DeleteButton_Click;
    }

    private void DeleteButton_Click(object sender, RoutedEventArgs e)
    {
        Value = DefaultValue;
    }
}

顺便说一句,

FindDescendant()
来自CommunityToolkit.WinUI.ExtensionsNuGet包。

© www.soinside.com 2019 - 2024. All rights reserved.