WPF用户控件显示一个月总值的年份和月份

时间:2010-12-08 07:06:05

标签: wpf user-controls binding

我在数据库中有一个值,即总月数。在我的WPF UI中,我需要显示并更新此值作为年数和月数。我正在努力让绑定在这个控件中工作,这样我就可以使用两个单独的文本框(年和月)来查看和更新​​这个月的总值

任何人都可以帮忙吗?

2 个答案:

答案 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>