XAML (WinUI)DatePicker SelectedDate Binding空问题(x:Bind和Binding是不同的结果)

8gsdolmq  于 2023-05-11  发布在  其他
关注(0)|答案(1)|浏览(117)

(WInUI 3)DatePicker SelectedDate x:Bind和Binding是不同的结果??x:Bind => SelectedDate为null Binding => SelectedDate为1923-1-1
结果图像:

怎么办让绑定也为null?
验证码:

<DatePicker SelectedDate="{x:Bind vm.MyDate, Mode=TwoWay}"/>
<StackPanel DataContext="{x:Bind vm}">
   <DatePicker SelectedDate="{Binding MyDate}"/>
</StackPanel>
public class MyTable : ObservableObject
{
    private DateTimeOffset? _mydate;
    public DateTimeOffset? MyDate
    {
        get => _mydate;
        set => SetProperty(ref _mydate, value);
    }
}
public sealed partial class MainWindow : Window
{
    MyTable vm = new MyTable();
    public MainWindow() { this.InitializeComponent(); }
}
xdyibdwo

xdyibdwo1#

看起来Binding没有传递null的值,而是将其转换为某个默认值。这可能是因为DateTimeOffsetstruct
无论如何,这里有一个创建自定义控件的解决方法:

public class CustomDatePicker : DatePicker
{
    public CustomDatePicker()
    {
        this.RegisterPropertyChangedCallback(DatePicker.SelectedDateProperty, OnSelectedDatePropertyChanged);
    }

    private void OnSelectedDatePropertyChanged(DependencyObject sender, DependencyProperty dp)
    {
        if (this.SelectedDate <= this.MinYear)
        {
            this.SelectedDate = null;
        }
    }
}

它同时适用于Bindingx:Bind

<local:CustomDatePicker SelectedDate="{x:Bind ViewModel.MyDate, Mode=TwoWay}" />
<StackPanel DataContext="{x:Bind ViewModel}">
    <local:CustomDatePicker SelectedDate="{Binding MyDate, Mode=TwoWay}" />
</StackPanel>

相关问题