我在数据库中有一个值,即总月数。在我的WPF UI中,我需要显示并更新此值作为年数和月数。我正在努力让绑定在这个控件中工作,这样我就可以使用两个单独的文本框(年和月)来查看和更新这个月的总值
任何人都可以帮忙吗?
答案 0 :(得分:0)
在作为绑定源的类(例如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
接口,并在PropertyChanged
的值发生更改时为这两个属性引发_timeInMonths
事件。
答案 1 :(得分:0)
我想您应该使用转换器将月份值转换为相应的年和月值。或者您可以在viewmodel本身中执行此操作
样品
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>