6

如何以编程方式执行以下操作(来自 XAML):

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

public DateTime OrderDate

现在我有以下

TextBox txtboxOrderdDate = new TextBox();

而且我知道我需要做类似的事情

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

但是我被困在这里......不确定如何继续应用 StringFormat,也不确定 SOURCE 是正确的方法(我应该使用 ElementName 吗?)

4

4 回答 4

9

设为MainWindow类名。MainWindow将以下代码更改为您的班级名称。

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


}
于 2013-05-15T06:23:30.370 回答
0

您是否尝试将bindingOrderDate'StringFormat属性设置为正确的格式?根据 MSDN,这就是它应该如何工作的。

于 2013-05-15T06:07:13.950 回答
-1

在后面的代码中定义类型的属性,DateTime然后绑定。

请参考此链接

于 2013-05-15T06:20:40.730 回答
-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]
于 2013-05-15T06:51:45.113 回答