prosource

WPF 날짜 선택기의 문자열 형식 변경

probook 2023. 4. 28. 21:08
반응형

WPF 날짜 선택기의 문자열 형식 변경

WPF Toolkit DatePicker에서 구분 기호에 슬래시 대신 하이픈을 사용하도록 DatePickerTextBox의 문자열 형식을 변경해야 합니다.

이 기본 문화 또는 표시 문자열 형식을 재정의할 수 있는 방법이 있습니까?

01-01-2010

저는 이 코드의 도움으로 이 문제를 해결했습니다.여러분 모두에게도 도움이 되길 바랍니다.

<Style TargetType="{x:Type DatePickerTextBox}">
 <Setter Property="Control.Template">
  <Setter.Value>
   <ControlTemplate>
    <TextBox x:Name="PART_TextBox"
     Text="{Binding Path=SelectedDate, StringFormat='dd MMM yyyy', 
     RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}}" />
   </ControlTemplate>
  </Setter.Value>
 </Setter>
</Style>

Wonko의 답변에 따르면 날짜 형식을 Xaml 형식으로 지정하거나 날짜 선택기에서 상속하여 지정할 수 없습니다.

현재 스레드에 대한 ShortDateFormat을 재정의하는 다음 코드를 myView의 생성자에 넣었습니다.

CultureInfo ci = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
ci.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy";
Thread.CurrentThread.CurrentCulture = ci;

WPF 툴킷DateTimePicker이제는Format재산과FormatString소유물.지정하는 경우Custom형식 유형으로 고유한 형식 문자열을 제공할 수 있습니다.

<wpftk:DateTimePicker
    Value="{Binding Path=StartTime, Mode=TwoWay}"
    Format="Custom"
    FormatString="MM/dd/yyyy hh:mmtt"/>

수락된 답변(고맙다 @petrycol)은 저를 올바른 방향으로 이끌었지만, 실제 달력 보기 내에서 다른 텍스트 상자 테두리와 배경색을 얻고 있었습니다.다음 코드를 사용하여 수정했습니다.

        <Style TargetType="{x:Type Control}" x:Key="DatePickerTextBoxStyle">
            <Setter Property="BorderThickness" Value="0"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
            <Setter Property="Background" Value="{x:Null}"/>
        </Style>

        <Style TargetType="{x:Type DatePickerTextBox}" >
            <Setter Property="Control.Template">
                <Setter.Value>
                    <ControlTemplate>
                        <TextBox x:Name="PART_TextBox"
                             Text="{Binding Path=SelectedDate, StringFormat='dd-MMM-yyyy', RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}}" Style="{StaticResource DatePickerTextBoxStyle}" >
                        </TextBox>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

참고: 이 답변(원래 2010년 작성)은 이전 버전을 위한 것입니다.최신 버전의 사용자 지정 형식 사용에 대한 다른 답변 보기

안타깝게도 XAML을 말하는 경우 SelectedDateFormat을 "Long" 또는 "Short"로 설정해야 합니다.

바이너리와 함께 툴킷 소스를 다운로드한 경우 툴킷이 어떻게 정의되는지 확인할 수 있습니다.다음은 해당 코드의 주요 내용입니다.

DatePicker.cs

#region SelectedDateFormat

/// <summary>
/// Gets or sets the format that is used to display the selected date.
/// </summary>
public DatePickerFormat SelectedDateFormat
{
    get { return (DatePickerFormat)GetValue(SelectedDateFormatProperty); }
    set { SetValue(SelectedDateFormatProperty, value); }
}

/// <summary>
/// Identifies the SelectedDateFormat dependency property.
/// </summary>
public static readonly DependencyProperty SelectedDateFormatProperty =
    DependencyProperty.Register(
    "SelectedDateFormat",
    typeof(DatePickerFormat),
    typeof(DatePicker),
    new FrameworkPropertyMetadata(OnSelectedDateFormatChanged),
    IsValidSelectedDateFormat);

/// <summary>
/// SelectedDateFormatProperty property changed handler.
/// </summary>
/// <param name="d">DatePicker that changed its SelectedDateFormat.</param>
/// <param name="e">DependencyPropertyChangedEventArgs.</param>
private static void OnSelectedDateFormatChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    DatePicker dp = d as DatePicker;
    Debug.Assert(dp != null);

    if (dp._textBox != null)
    {
        // Update DatePickerTextBox.Text
        if (string.IsNullOrEmpty(dp._textBox.Text))
        {
            dp.SetWaterMarkText();
        }
        else
        {
            DateTime? date = dp.ParseText(dp._textBox.Text);

            if (date != null)
            {
                dp.SetTextInternal(dp.DateTimeToString((DateTime)date));
            }
        }
    }
}



#endregion SelectedDateFormat

private static bool IsValidSelectedDateFormat(object value)
{
    DatePickerFormat format = (DatePickerFormat)value;

    return format == DatePickerFormat.Long
        || format == DatePickerFormat.Short;
}

private string DateTimeToString(DateTime d)
{
    DateTimeFormatInfo dtfi = DateTimeHelper.GetCurrentDateFormat();

    switch (this.SelectedDateFormat)
    {
        case DatePickerFormat.Short:
            {
                return string.Format(CultureInfo.CurrentCulture, d.ToString(dtfi.ShortDatePattern, dtfi));
            }

        case DatePickerFormat.Long:
            {
                return string.Format(CultureInfo.CurrentCulture, d.ToString(dtfi.LongDatePattern, dtfi));
            }
    }      

    return null;
}

DatePickerFormat.cs

public enum DatePickerFormat
{
    /// <summary>
    /// Specifies that the date should be displayed 
    /// using unabbreviated days of the week and month names.
    /// </summary>
    Long = 0,

    /// <summary>
    /// Specifies that the date should be displayed 
    ///using abbreviated days of the week and month names.
    /// </summary>
    Short = 1
}

XAML

 <DatePicker x:Name="datePicker" />

C#

var date = Convert.ToDateTime(datePicker.Text).ToString("yyyy/MM/dd");

ToString("")에 원하는 형식을 입력합니다. 예를 들어 ToString("dd MMM yyy") 및 출력 형식은 2017년 6월 7일입니다.

변환기 클래스:

public class DateFormat : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null) return null;
        return ((DateTime)value).ToString("dd-MMM-yyyy");
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

wpf 태그

<DatePicker Grid.Column="3" SelectedDate="{Binding DateProperty, Converter={StaticResource DateFormat}}" Margin="5"/>

도움이 되길 바랍니다.

위치에 따라 표시되는 형식은 다음과 같습니다.

  ValueStringFormat="{}{0:MM'-'yy}" />

그리고 당신은 행복할 것입니다! (dd'-'MM'-'yyy)

Ben Pearce가 대답했듯이 CultureInfo 클래스를 사용하여 사용자 지정 형식을 처리할 수 있습니다. 이것이 유일한 논리적인 방법이라고 생각합니다.또한 형식이 다른 dateTimePickers가 있는 경우 다음을 사용할 수 있습니다.

CultureInfo ci = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
ci.DateTimeFormat.LongDatePattern = "MMM.yyyy"; //This can be used for one type of DatePicker
ci.DateTimeFormat.ShortDatePattern = "dd.MMM.yyyy"; //for the second type
Thread.CurrentThread.CurrentCulture = ci;

그런 다음 .xaml 문서에서 날짜 형식을 변경하면 됩니다.

  <DatePicker Name="dateTimePicker1" SelectedDateFormat="Long"  />

언급URL : https://stackoverflow.com/questions/3819832/changing-the-string-format-of-the-wpf-datepicker

반응형