1

I should have a custom format for my DatePicker DisplayDate, but my problem is, that format can't be made with the standard custom format tags (like y, yyyy, d and so on).

Is there a way you can bind the SelectedDate to a DateTime property and the DisplayText to a string property?

Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123
Gragnil
  • 13
  • 2

3 Answers3

0

Well you can use StringFormat for specific DatePicker date format (check this example: Changing the string format of the WPF DatePicker)

Here is a simple example (make sure ViewModel is proper DataContext for you xaml file)

Main Window

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        var vm = new ViewModel();
        DataContext = vm;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var context = (ViewModel) DataContext;
        var date = context.SelectedDate;
        MessageBox.Show(string.Format("Selected Date is {0:MM/dd/yy H:mm:ss zzz}", date));
    }
}

View Model

public class ViewModel
{
    public DateTime SelectedDate { get; set; }
}

Xaml file

 <DatePicker VerticalAlignment="Top"
                SelectedDate="{Binding SelectedDate}" />
 <Button Content="Button"
         HorizontalAlignment="Left"
         Margin="10,74,0,0"
         VerticalAlignment="Top"
         Width="75"
         Click="Button_Click" />

You can change the format of DateTime when you show the MessageBox (check this: https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx)

UPDATE

For (yy-day Of Year), you can use:

MessageBox.Show(string.Format("Selected Date is {0:yy-}{1}", date, date.DayOfYear));
Community
  • 1
  • 1
Shmwel
  • 1,697
  • 5
  • 26
  • 43
  • Ah thanks, so with the standart control it is only possible with a additional control (like the button), not directly in the textbox from the datepicker. I think then i don't get around a UserControl. – Gragnil Jul 16 '15 at 07:19
  • You can apply some events on your DatePicker if you want. I don't get exactly what is your target. But, if you want more information, I am available to answer your questions:). [Also, you can make a custom `UserControl` but, you can use already DatePicker. If you want to show at runtime in DatePicker's textbox you can do a Converter which does that (formats your format) – Shmwel Jul 16 '15 at 07:39
0

I think you can use string format property to display date in a custom way

  Binding="{Binding CustomerParcelDropTime,StringFormat=\{0:dd/MM/yyyy HH:mm:ss \}}"
Justin CI
  • 2,693
  • 1
  • 16
  • 34
0

Thanks for your answer. My problem is that there is no format for what i need. I need tho show the year in two digits (yy) but after that i need the day of year and for that is no format. My current solution is to write a UserControl with a ordanary TextBox and a Calendar Popup. I just hoped i can use a standart control.

Gragnil
  • 13
  • 2