如何使用stringformat以编程方式设置文本框的绑定?

时间:2013-05-15 05:59:45

标签: c# wpf textbox

如何以编程方式执行以下操作(来自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 个答案:

答案 0 :(得分:8)

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


}

答案 1 :(得分:0)

您是否尝试将bindingOrderDate的{​​{1}}属性设置为正确的格式?据MSDN称,它应该如何运作。

答案 2 :(得分:-1)

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

请参阅此link

答案 3 :(得分:-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]