WPF 编辑 DateTime 的小时和分钟

发布于 2024-09-02 01:51:51 字数 546 浏览 1 评论 0原文

我有 3 个文本框来编辑日期时间。 需要注意的是,这 2 个文本框正在编辑第一个文本框日期时间值的小时和分钟。 1 编辑日期,2 编辑小时和分钟。 你会怎么做?下面的代码在编辑小时或分钟时不反映 DateTime 更改,因为它会执行 ToString("HH") 并且 DateTime 值丢失:

 <TextBox Text="{Binding MyDateTime}"  />

    <!--This cannot work : it's just for clearing purposes -->
    <TextBox Text="{Binding MyDateTime, StringFormat=\{0:HH\}}}"  />
    <TextBox Text="{Binding MyDateTime}, StringFormat=\{0:mm\}}"  />

当然,我可以将 ViewModel 作为 DataContext,在其中以编程方式解决它。 但我只是想知道是否有直接在 XAML 中的可能性

I have 3 TextBoxes to edit a DateTime.
What is important to notice is that those 2 TextBoxes are editing the hour and minutes of the first TextBox DateTime value.
One to edit the Date and 2 to edit hour and minutes.
How would you do that? The code below doesn't reflect the DateTime changes when editing the hour or minute, because it does ToString("HH") and the DateTime value is lost:

 <TextBox Text="{Binding MyDateTime}"  />

    <!--This cannot work : it's just for clearing purposes -->
    <TextBox Text="{Binding MyDateTime, StringFormat=\{0:HH\}}}"  />
    <TextBox Text="{Binding MyDateTime}, StringFormat=\{0:mm\}}"  />

Of course I can have a ViewModel as DataContext where I would solve it programmatically.
But I just want to know if there is any possiblity directly in XAML

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

幽梦紫曦~ 2024-09-09 01:51:52

仅使用 XAML 是不容易实现的。有几种可能性可以解决这个问题:

1。编写可以执行此操作的自定义控件或用户控件

您可以编写一个自定义控件/用户控件(例如 DateTimeTextBox),它具有您的 xaml 可以绑定的属性 DateTime Value 并且包含逻辑转换为在两个文本框之一中输入的日期时间值。除了两个文本框之外,您还可以使用类似 maskedtextbox 的内容。

2. ViewModel 中的两个专用属性

如果您使用 MVVM,您可以为 ViewModel 提供两个专用属性 int DateTimeHours int DateTimeMinutes 并与之绑定:

<TextBox Text="{Binding MyDateTimeHours}"  />
<TextBox Text="{Binding MyDateTimeMinutes}"  />

然后您的 ViewModel 将将两个属性合并为一个日期时间值。

It is not easily possible with XAML only. There are several possibilities how to solve this:

1. Write custom control or user control that can do this

You could wirte a custom control / user control (e.g. DateTimeTextBox) that has a Property DateTime Value that your xaml can bind against and that contains logic to convert to the datetime value entered in one of its two textboxes. Instead of two textboxes you could also have something like maskedtextbox.

2. Two dedicated properties in the ViewModel

If you go with MVVM you could give your ViewModel two dedicated properties int DateTimeHours int DateTimeMinutes and bind against that:

<TextBox Text="{Binding MyDateTimeHours}"  />
<TextBox Text="{Binding MyDateTimeMinutes}"  />

Your ViewModel would then merge the two properties to a single DateTime value.

早茶月光 2024-09-09 01:51:52

您将需要使用具有 2way 绑定和转换器参数的转换器。将原始小时保存在转换器中。然后您可以适当地更新绑定源。

You will need to use a converter with 2way binding and a converter parameter. Save the original hour in the Converter. Then you can update the binding source appropriately.

本王不退位尔等都是臣 2024-09-09 01:51:52

我很欣赏这是一篇旧文章,但我今天遇到了这个并找到了另一种处理日期和时间绑定的方法。

我创建了一个名为 dateTime 的分部类,它有 4 个属性,其中一个表示日期,1 个表示小时,另一个表示分钟。然后是返回完整日期的只读 dateTime 属性。

    Partial Public Class dateTimeValue
        Property Dt As Date
        Property Hr As Integer
        Property Mn As Integer

        ReadOnly Property dateTime As Date
            Get
                Dim d = Dt
                d = d.AddHours(d.Hour * -1).AddHours(Hr)
                d = d.AddMinutes(d.Minute * -1).AddMinutes(Mn)
                d = d.AddSeconds(d.Second * -1)
                Return d
            End Get
        End Property
    End Class

然后,在 XAML 中,我使用了网格布局,并绑定了 DateTimePicker 和几个 ComboBox。

            <UniformGrid Columns="2">
                <TextBlock Text="Date"/>
                <DatePicker SelectedDate="{Binding dateTime.Dt}"/>
                <TextBlock Text="Time"/>
                <WrapPanel>
                    <ComboBox SelectedValue="{Binding dateTime.Hr}" SelectedValuePath="Content">
                        <ComboBoxItem>00</ComboBoxItem>
                        <ComboBoxItem>01</ComboBoxItem>
                        <ComboBoxItem>02</ComboBoxItem>
                        .........
                        <ComboBoxItem>22</ComboBoxItem>
                        <ComboBoxItem>23</ComboBoxItem>
                    </ComboBox>
                    <TextBlock Text=":"/>
                    <ComboBox SelectedValue="{Binding dateTime.Mn}" SelectedValuePath="Content">
                        <ComboBoxItem>00</ComboBoxItem>
                        <ComboBoxItem>15</ComboBoxItem>
                        <ComboBoxItem>30</ComboBoxItem>
                        <ComboBoxItem>45</ComboBoxItem>
                    </ComboBox>
                </WrapPanel>
                <Button Click="saveTask" Content="Save Task"/>
            </UniformGrid>

然后,要在文本块中显示正确的日期和时间,您可以使用

<TextBlock Text="{Binding dateTime.dateTime, StringFormat={}{0:dd MMM yyyy - HH:mm}}"/>

希望这可以帮助其他人。

I appreciate this is an old post, but I came across this today and found another way to handle bindings with date and time.

I created a partial class called dateTime with 4 properties one for the date, 1 for hour and another for minutes. Then a readonly dateTime property that returns a completed date.

    Partial Public Class dateTimeValue
        Property Dt As Date
        Property Hr As Integer
        Property Mn As Integer

        ReadOnly Property dateTime As Date
            Get
                Dim d = Dt
                d = d.AddHours(d.Hour * -1).AddHours(Hr)
                d = d.AddMinutes(d.Minute * -1).AddMinutes(Mn)
                d = d.AddSeconds(d.Second * -1)
                Return d
            End Get
        End Property
    End Class

Then in the XAML I used a grid layout with the bindings to a DateTimePicker and a couple of ComboBoxes.

            <UniformGrid Columns="2">
                <TextBlock Text="Date"/>
                <DatePicker SelectedDate="{Binding dateTime.Dt}"/>
                <TextBlock Text="Time"/>
                <WrapPanel>
                    <ComboBox SelectedValue="{Binding dateTime.Hr}" SelectedValuePath="Content">
                        <ComboBoxItem>00</ComboBoxItem>
                        <ComboBoxItem>01</ComboBoxItem>
                        <ComboBoxItem>02</ComboBoxItem>
                        .........
                        <ComboBoxItem>22</ComboBoxItem>
                        <ComboBoxItem>23</ComboBoxItem>
                    </ComboBox>
                    <TextBlock Text=":"/>
                    <ComboBox SelectedValue="{Binding dateTime.Mn}" SelectedValuePath="Content">
                        <ComboBoxItem>00</ComboBoxItem>
                        <ComboBoxItem>15</ComboBoxItem>
                        <ComboBoxItem>30</ComboBoxItem>
                        <ComboBoxItem>45</ComboBoxItem>
                    </ComboBox>
                </WrapPanel>
                <Button Click="saveTask" Content="Save Task"/>
            </UniformGrid>

Then to display the correct date and time in say a textblock you can use

<TextBlock Text="{Binding dateTime.dateTime, StringFormat={}{0:dd MMM yyyy - HH:mm}}"/>

Hope this helps someone else out.

︶葆Ⅱㄣ 2024-09-09 01:51:52

100% MVVM

public class DateTimeConverter : IValueConverter
{
    private DateTime _target = DateTime.Now;
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var source = value as DateTime?;
        if (source is null) return null;
        _target = source.Value;
        switch (parameter as string)
        {
            case "y": return source.Value.Year;
            case "m": return source.Value.Month;
            case "d": return source.Value.Day;
            case "h": return source.Value.Hour;
            case "i": return source.Value.Minute;
            default: return null;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        switch (parameter as string)
        {
            case "y": return new DateTime(System.Convert.ToInt32(value), _target.Month, _target.Day, _target.Hour, _target.Minute, 0);
            case "m": return new DateTime(_target.Year, System.Convert.ToInt32(value), _target.Day, _target.Hour, _target.Minute, 0);
            case "d": return new DateTime(_target.Year, _target.Month, System.Convert.ToInt32(value), _target.Hour, _target.Minute, 0);
            case "h": return new DateTime(_target.Year, _target.Month, _target.Day, System.Convert.ToInt32(value), _target.Minute, 0);
            case "i": return new DateTime(_target.Year, _target.Month, _target.Day, _target.Hour, System.Convert.ToInt32(value), 0);
            default: return _target;
        }
    }
}

100% MVVM

public class DateTimeConverter : IValueConverter
{
    private DateTime _target = DateTime.Now;
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var source = value as DateTime?;
        if (source is null) return null;
        _target = source.Value;
        switch (parameter as string)
        {
            case "y": return source.Value.Year;
            case "m": return source.Value.Month;
            case "d": return source.Value.Day;
            case "h": return source.Value.Hour;
            case "i": return source.Value.Minute;
            default: return null;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        switch (parameter as string)
        {
            case "y": return new DateTime(System.Convert.ToInt32(value), _target.Month, _target.Day, _target.Hour, _target.Minute, 0);
            case "m": return new DateTime(_target.Year, System.Convert.ToInt32(value), _target.Day, _target.Hour, _target.Minute, 0);
            case "d": return new DateTime(_target.Year, _target.Month, System.Convert.ToInt32(value), _target.Hour, _target.Minute, 0);
            case "h": return new DateTime(_target.Year, _target.Month, _target.Day, System.Convert.ToInt32(value), _target.Minute, 0);
            case "i": return new DateTime(_target.Year, _target.Month, _target.Day, _target.Hour, System.Convert.ToInt32(value), 0);
            default: return _target;
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文