You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为自定义NumericUpDown控件创建可绑定的TextChanged事件

自定义NumericUpDown添加可绑定TextChanged事件的实现方案

1. 定义控件的TextChanged事件

在NumericUpDown类中声明公开的TextChanged事件,复用Xamarin.Forms内置的TextChangedEventArgs传递新旧文本值:

public event EventHandler<TextChangedEventArgs> TextChanged;

2. 转发内部输入框的文本变化事件

在控件构造函数中,订阅内部_entry的TextChanged事件,将事件逻辑转发到自定义控件的事件上:

public NumericUpDown() : base()
{
    BindingContext = this;
    _grid = new Grid();
    _entry = new CustomNumericUpDownEntry();
    _stackLayout = new StackLayout();
    _btnup = new Button();
    _btndown = new Button();

    // 绑定内部输入框的文本变化事件
    _entry.TextChanged += OnEntryTextChanged;

    // ... 原有初始化代码 ...

    _stackLayout.Children.Add(_btndown);
    _stackLayout.Children.Add(_btnup);
    _grid.Children.Add(_entry);
    _grid.Children.Add(_stackLayout);

    Content = _grid;
}

private void OnEntryTextChanged(object sender, TextChangedEventArgs e)
{
    // 触发自定义控件的TextChanged事件
    TextChanged?.Invoke(this, e);
}

3. 可选:添加MVVM命令绑定支持

如果需要在MVVM模式下通过命令处理文本变化,添加两个可绑定属性:

// 文本变化命令属性
public static readonly BindableProperty TextChangedCommandProperty =
    BindableProperty.Create(nameof(TextChangedCommand), typeof(ICommand), typeof(NumericUpDown));

public ICommand TextChangedCommand
{
    get => (ICommand)GetValue(TextChangedCommandProperty);
    set => SetValue(TextChangedCommandProperty, value);
}

// 命令参数属性
public static readonly BindableProperty TextChangedCommandParameterProperty =
    BindableProperty.Create(nameof(TextChangedCommandParameter), typeof(object), typeof(NumericUpDown));

public object TextChangedCommandParameter
{
    get => GetValue(TextChangedCommandParameterProperty);
    set => SetValue(TextChangedCommandParameterProperty, value);
}

修改事件处理方法,同时执行绑定的命令:

private void OnEntryTextChanged(object sender, TextChangedEventArgs e)
{
    TextChanged?.Invoke(this, e);
    
    // 执行绑定的命令,可传递事件参数或自定义参数
    TextChangedCommand?.Execute(TextChangedCommandParameter ?? e);
}

使用示例

代码后台绑定事件

var numUpDown = new NumericUpDown();
numUpDown.TextChanged += (s, e) => 
{
    Console.WriteLine($"旧值:{e.OldTextValue},新值:{e.NewTextValue}");
};

XAML中绑定事件或命令

<customitems:NumericUpDown
    Margin="10,0"
    BackgroundColor="Transparent"
    BorderColor="red"
    ButtonBackgroundColor="Purple"
    ButtonCornerRadius="15"
    CornerRadius="15"
    HorizontalOptions="Center"
    TextChanged="NumericUpDown_TextChanged"
    TextChangedCommand="{Binding OnTextChangedCommand}"
    TextChangedCommandParameter="{Binding SelectedItem}" />

内容的提问来源于stack exchange,提问作者BySuspect

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 04:48:20