[英]c# WPF DatePicker to Label Binding, to get a persons age
My job is to bind a labels Content in XAML to a DatePicker, which is a persons birth date, to get their age. 我的工作是将XAML中的标签Content绑定到DatePicker(这是一个人的出生日期)以获取年龄。 For example: Date picker: 2000.1.1 Label: 16. How do I do this? 例如:日期选择器:2000.1.1标签:16.我该怎么做?
edit 编辑
The label needs to change immediately when the DatePicker change. 当DatePicker更改时,标签需要立即更改。
Bind your label using an IValueConverter implementation such as the following: 使用IValueConverter实现绑定标签,例如:
class BirthdateToAgeConverter : IValueConverter
{
public object Convert
(
object value,
Type targetType,
object parameter,
string language)
{
var birthdate = ((DateTime) value).Date;
var age = DateTime.Today.Year - birthdate.Year;
if (birthdate > DateTime.Today.AddYears(-age))
{
age--;
}
return age;
}
public object ConvertBack
(
object value,
Type targetType,
object parameter,
string language)
{
throw new NotImplementedException();
}
}
Edit: In your XAML you need to define the binding path if you are binding directly to the DatePicker. 编辑:如果直接绑定到DatePicker,则需要在XAML中定义绑定路径。 You could also bind to SzuletesiDatum on your ViewModel. 您还可以在ViewModel上绑定到SzuletesiDatum。
<Label Content="{Binding ElementName=dtPicker, Path=SelectedDate ,Converter={StaticResource DTKC}}"
HorizontalAlignment="Left" Margin="356,94,0,0"
VerticalAlignment="Top"/>
<DatePicker x:Name="dtPicker"
SelectedDate="{Binding SzuletesiDatum}"
HorizontalAlignment="Left"
Margin="112,94,0,0"
VerticalAlignment="Top"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.