How to programmatically set the binding of a text field using stringformat?

How to programmatically do the following (from XAML):

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

Now i have

 TextBox txtboxOrderdDate = new TextBox(); 

And I know that I need to do something like

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

But I'm stuck here ... not sure how to get started with StringFormat, and I'm not sure SOURCE is the right way (should I use ElementName?)

+6
source share
4 answers

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

 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); } 
+8
source

Have you tried setting the bindingOrderDate StringFormat property in the correct format? How it should work, according to MSDN.

0
source

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

Please refer to this link .

-1
source
  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] 
-2
source

Source: https://habr.com/ru/post/945038/


All Articles