Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programatically set the binding of a textbox with stringformat?

Tags:

c#

wpf

textbox

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?)

like image 644
JSchwartz Avatar asked May 15 '13 05:05

JSchwartz


1 Answers

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);


}
like image 87
Ramesh Durai Avatar answered Oct 17 '22 17:10

Ramesh Durai