【发布时间】:2010-12-08 07:06:04
【问题描述】:
我在数据库中有一个值,即总月数。在我的 WPF UI 中,我需要将此值显示和更新为年数和月数。我正在努力让绑定在此控件中工作,以便我可以使用两个单独的文本框(年和月)查看和更新总月数的这个值
有人可以帮忙吗?
【问题讨论】:
-
你需要双向绑定,对吧?
标签: wpf user-controls binding
我在数据库中有一个值,即总月数。在我的 WPF UI 中,我需要将此值显示和更新为年数和月数。我正在努力让绑定在此控件中工作,以便我可以使用两个单独的文本框(年和月)查看和更新总月数的这个值
有人可以帮忙吗?
【问题讨论】:
标签: wpf user-controls binding
在作为绑定源的类(例如 ViewModel)中,您可以添加两个属性,以便在需要时计算这两个值。例如:
private const int MonthsInAYear = 12; // pedagogic purposes only :)
// This field contains the updated database value
private int _timeInMonths;
public int TimeYears
{
get { return _timeInMonths / MonthsInAYear; }
}
public int TimeMonths
{
get { return _timeInMonths % MonthsInAYear; }
}
如果您希望这些值自动更新,请让此类实现INotifyPropertyChanged 接口,并在_timeInMonths 的值更改时为这两个属性引发PropertyChanged 事件。
【讨论】:
我想您应该使用转换器将您的月份值转换为相应的年份和月份值。或者您可以在视图模型本身中进行此操作
样本
public class MonthConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if(((string)parameter)=="Year")
{
return (int)value / 12;
}
if (((string)parameter) == "Month")
{
return (int)value % 12;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
在你的 xaml 中
<StackPanel Orientation="Horizontal">
<TextBlock Height="23" Text="{Binding TotalMonths,Converter={StaticResource MonthConverter},ConverterParameter='Year',StringFormat={}{0}Years}"/>
<TextBlock Height="23" Text="{Binding TotalMonths,Converter={StaticResource MonthConverter},ConverterParameter='Month',StringFormat={}{0}Months}"/>
</StackPanel>
【讨论】: