首页 > 解决方案 > 无论初始选定的日期值如何使两个 WPF DatePicker-s 以不同的宽度显示?

问题描述

当一个具有as和另一个初始化为not null时,两个DatePicker控件最初显示为不同。WidthSelectedDatenullDateTime

这里的问题陈述是 - 在用户将日期值输入到具有null初始值的控件后,它Width保持不变。

如何配置DatePicker初始显示,使其大小相同,无论初始是否SelectedDate为空

XAML 中有以下布局定义:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Grid Grid.Row="0" Margin="5">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <DatePicker SelectedDate="{Binding Path=SelectedDate1, Mode=TwoWay}"/>
    </Grid>
    <Grid Grid.Row="1" Margin="5">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <DatePicker SelectedDate="{Binding Path=SelectedDate2, Mode=TwoWay}"/>
    </Grid>
</Grid>

并且视图模型具有以下属性定义:

private DateTime? _selectedDate1;
private DateTime? _selectedDate2 = DateTime.Now;
public DateTime? SelectedDate1
{
    get { return _selectedDate1; }
    set
    {
        _selectedDate1 = value;
        OnPropertyChanged(nameof(SelectedDate1));
    }
}
public DateTime? SelectedDate2
{
    get { return _selectedDate2; }
    set
    {
        _selectedDate2 = value;
        OnPropertyChanged(nameof(SelectedDate2));
    }
}

标签: c#wpfxamldatepicker

解决方案


<Grid>
<Grid.RowDefinitions>
    <RowDefinition Height="35"/>
    <RowDefinition Height="35"/>
    <RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
    <ColumnDefinition Width="300"/>
    <ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>

<DatePicker Grid.Row="0" Grid.Column="0"
    SelectedDate="{Binding Path=SelectedDate1, Mode=TwoWay}"/>

<DatePicker Grid.Row="1" Grid.Column="0"
    SelectedDate="{Binding Path=SelectedDate2, Mode=TwoWay}"/>

推荐阅读