我如何以编程方式(从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吗?)
最佳答案
令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);
}
关于c# - 如何以编程方式设置具有stringformat的文本框的绑定(bind)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16557887/