WinUI自定义仅支持Nullable Long的文本框首次加载后端数据时UI不显示值的问题
WinUI自定义仅支持Nullable Long的文本框首次加载后端数据时UI不显示值的问题
我最近在WinUI里做了个自定义文本框,专门用来输入可空长整型(nullable long)的值,结果碰到个奇怪的问题:第一次从后端加载数据的时候,明明绑定的属性已经拿到值了,UI上却完全不显示;不过之后在UI上手动修改值的时候,一切又都正常工作。下面是我的实现代码:
自定义控件代码(Code-behind)
using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml; namespace Conversion.Common { public class NullableLongNumberBox : TextBox { public static readonly DependencyProperty ValueProperty = DependencyProperty.Register( nameof(Value), typeof(long?), typeof(NullableLongNumberBox), new PropertyMetadata(null, OnValuePropertyChanged)); public NullableLongNumberBox() { BeforeTextChanging += NullableLongNumberBox_BeforeTextChanging; TextChanging += NullableLongNumberBox_TextChanging; } public long? Value { get => (long?)GetValue(ValueProperty); set => SetValue(ValueProperty, value); } private int NextCaretPosition { get; set; } private static void OnValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is NullableLongNumberBox nullableLongNumberBox) { nullableLongNumberBox.Text = e.NewValue?.ToString() ?? string.Empty; } } private void NullableLongNumberBox_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args) { sender.SelectionStart = NextCaretPosition; } private void NullableLongNumberBox_BeforeTextChanging(TextBox sender, TextBoxBeforeTextChangingEventArgs args) { if (string.IsNullOrEmpty(args.NewText)) { Value = null; return; } if (!long.TryParse(args.NewText, out long value)) { args.Cancel = true; return; } NextCaretPosition = sender.SelectionStart; Value = value; } } }
XAML 使用代码
<common:NullableLongNumberBox x:Name="longPengeoUpdate" Grid.Column="5" Width="150" Style="{StaticResource NumericTextBoxRightAlignStyle}" Value="{Binding PengeoUpdate, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />
备注:内容来源于stack exchange,提问作者SANJEEV PRATAP Singh
相关产品推荐
相关产品推荐

