覆盖 NumberBox 清除按钮 WinUI 3 的默认行为

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

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

c# mvvm winui-3 winui winui-xaml
2个回答
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包。


0
投票

安德鲁的回答足够清楚了。我只是想展示另一种通过 VisualTreeHelper 类查找删除按钮的方法。

代码在这里:

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

你可以这样使用它:

    var deletebutton = FindChildByName(targetControl, "DeleteButton") as TextBlock;
    deletebutton.Text = "New Content";
© www.soinside.com 2019 - 2024. All rights reserved.