在 TextBox WPF 中传递短日期

Passing short date in TextBox WPF

你好,我有一个 dataGrid,双击它会打开一个新的 Window 并填充一些 TextBoxes 我的问题是 Textboxes 正在显示日期和时间,而我希望它显示短日期。

我已经将我的 SQL 服务器数据库配置为严格 Date 并且它在数据库中显示了短日期,所以我不确定为什么它在我的 DateTime 中传递Textbox

请帮忙!

这是我的代码 Window 1:

        private void dtGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {

        // User double clicks on DataGrid Row
        // Open new Window
        // Populate selected textboxes with selected datarow
        DataGrid gd = (DataGrid)sender;
        DataRowView row_selected = gd.SelectedItem as DataRowView;

        var windowToOpen = new Window1();

        if (gd != null)
        {
            // Textboxes
            windowToOpen.txt_RowRecrd.Text = row_selected["DSP_ID"].ToString();
            windowToOpen.txt_DateResolved.Text = row_selected["DATERSLVD"].ToString();
            windowToOpen.txt_revcls.Text = row_selected["RateType"].ToString();

            windowToOpen.Show();
       }
    }

这是我在 Window 2 中的 TextBoxes 之一的 XAML:

                        <TextBox
                        x:Name="txt_DateResolved"
                        Width="110"
                        Height="26"
                        Margin="5,0,0,0"
                        HorizontalAlignment="Left"
                        VerticalAlignment="Bottom"
                        Background="Transparent"
                        BorderBrush="Transparent"
                        BorderThickness="0"
                        Foreground="Black"
                        IsEnabled="True">
                    </TextBox>

因为在 C# 中你没有 Date 结构你只有 DateTime struct。在您的情况下,您可以在 ToString() 方法中格式化 DateTime。您应该有一个 DateTime 实例,您可以在其上调用以下方法:

dateTime.ToShortDateString()

dateTime.ToString("dd-MM-yy")

示例:

if (row_selected["DATERSLVD"] != null)
{   
  DateTime dateTime;
  if (DateTime.TryParse(row_selected["DATERSLVD"].ToString(), out dateTime))
  {
      windowToOpen.txt_DateResolved.Text = dateTime.ToShortDateString();
  }
  else
  {
      windowToOpen.txt_DateResolved.Text = ""; //assign default value
  }
}

尝试将从 DataRowView 返回的 object 转换为 DateTime,然后使用接受格式的 ToString 重载:

windowToOpen.txt_DateResolved.Text = Convert.ToDateTime(row_selected["DATERSLVD"])
    .ToString("yyyy-MM-dd");

您可能还想检查和处理 null 值:

windowToOpen.txt_DateResolved.Text = row_selected["DATERSLVD"] == DBNull.Value?
    string.Empty : Convert.ToDateTime(row_selected["DATERSLVD"]).ToString("yyyy-MM-dd");