7

How do I programmatically do the following (from the XAML):

<TextBox Name="OrderDateText"
         Text="{Binding Path=OrderDate, StringFormat=dd-MM-yyyy}"

public DateTime OrderDate

Right now I have the following

TextBox txtboxOrderdDate = new TextBox();

And I know I need to do something like

  Binding bindingOrderDate = new Binding();
  bindingOrderDate.Source = "OrderDate";

But I am stuck here ... not sure how to proceed to apply the StringFormat nor am I sure that SOURCE is the correct way (should I be using ElementName?)

JSchwartz
  • 2,536
  • 6
  • 32
  • 45

4 Answers4

11

Let MainWindow be the Class Name. Change MainWindow in the below code to your class name.

public DateTime OrderDate
{
    get { return (DateTime) GetValue(OrderDateProperty); }
    set { SetValue(OrderDateProperty, value); }
}

public static readonly DependencyProperty OrderDateProperty =
    DependencyProperty.Register("OrderDate",
                                typeof (DateTime),  
                                typeof (MainWindow),
                                new PropertyMetadata(DateTime.Now, // Default value for the property
                                                     new PropertyChangedCallback(OnOrderDateChanged)));

private static void OnOrderDateChanged(object sender, DependencyPropertyChangedEventArgs args)
{
    MainWindow source = (MainWindow) sender;

    // Add Handling Code
    DateTime newValue = (DateTime) args.NewValue;
}

public MainWindow()
{
    InitializeComponent();

    OrderDateText.DataContext = this;
    var binding = new Binding("OrderDate")
        {
            StringFormat = "dd-MM-yyyy"
        };
    OrderDateText.SetBinding(TextBox.TextProperty, binding);

    //Testing
    OrderDate = DateTime.Now.AddDays(2);


}
Ramesh Durai
  • 2,666
  • 9
  • 32
  • 55
0

Have you tried setting the bindingOrderDate's StringFormat property to the proper format? That's how it should work, according to MSDN.

It'sNotALie.
  • 22,289
  • 12
  • 68
  • 103
-1

Define a property of type DateTime in your code behind and then bind.

Please refer this link.

Community
  • 1
  • 1
Haritha
  • 1,498
  • 1
  • 13
  • 35
-2
 Object data = new Object();

            TextBox txtboxOrderdDate = new TextBox();
            Binding bindingOrderDate = new Binding("Order Date", data, "OrderDate");
            bindingOrderDate.Format += new ConvertEventHandler(DecimalToCurrencyString);
            txtboxOrderdDate.DataBindings.Add(bindingOrderDate);

   private void DecimalToCurrencyString(object sender, ConvertEventArgs cevent)
        {

            if (cevent.DesiredType != typeof(string)) return;

            cevent.Value = ((decimal)cevent.Value).ToString("dd-MM-yyyy");
        }


//[For more information check MSDN][1]
Chamath Jeevan
  • 5,072
  • 1
  • 24
  • 27