2013-05-15 61 views
6

如何以編程方式執行下列操作(從XAML):如何以編程方式設置文本框與stringformat的綁定?

<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,也不確定源是否是正確的方式(我應該使用ElementName嗎?)

+0

檢查這個http://stackoverflow.com/questions/3099048/wpf-binding-and-dynamically-assigning-stringformat-property –

+0

無論'OrderDate'是一個datepicker? –

+0

定義的'OrderDate'屬性在哪裏? – Clemens

回答

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

public DateTime OrderDate – JSchwartz

0

您是否嘗試過將bindingOrderDateStringFormat屬性設置爲正確的格式?根據MSDN的說法,這就是它的工作原理。

-1

在代碼後面定義DateTime類型的屬性,然後綁定。請致電link

-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] 
相關問題