Patrik Valyon
Patrik Valyon

Reputation: 7

Override the default behaviour of the NumberBox clear button WinUI 3

I want to override the default behavior of the WinUI 3 NumberBox clear button, the default one resets the value to "0" but in my use case it would be much better If I could bind a specific command when the clear button is clicked. For example when I hit the button, it resets the value to "5" or to another default value.

Upvotes: 0

Views: 104

Answers (2)

Roy Li - MSFT
Roy Li - MSFT

Reputation: 8681

Andrew's answer is clear enough. I just want to show another way to find the DeleteButton via VisualTreeHelper class.

Code here:

  public static DependencyObject FindChildByName(DependencyObject parant, string ControlName)
  {
      int childCount = VisualTreeHelper.GetChildrenCount(parant);
      for (int i = 0; i < childCount; i++)
      {
          var MyChild = VisualTreeHelper.GetChild(parant, i);
          if (MyChild is FrameworkElement && ((FrameworkElement)MyChild).Name == ControlName)
              return MyChild;

          var FindResult = FindChildByName(MyChild, ControlName);
          if (FindResult != null)
              return FindResult;
      }
      return null;
  }

You could use it like this:

    var deletebutton = FindChildByName(targetControl, "DeleteButton") as TextBlock;
    deletebutton.Text = "New Content";

Upvotes: 0

Andrew KeepCoding
Andrew KeepCoding

Reputation: 13666

You can create a custom control that derives from the 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;
    }
}

BTW, FindDescendant() comes from the CommunityToolkit.WinUI.Extensions NuGet package.

Upvotes: 0

Related Questions