0

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.

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.