【问题标题】:WPF user control to display years and months from one total months valueWPF 用户控件显示来自一个总月值的年和月
【发布时间】:2010-12-08 07:06:04
【问题描述】:

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

有人可以帮忙吗?

【问题讨论】:

  • 你需要双向绑定,对吧?

标签: wpf user-controls binding


【解决方案1】:

在作为绑定源的类(例如 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 事件。

【讨论】:

    【解决方案2】:

    我想您应该使用转换器将您的月份值转换为相应的年份和月份值。或者您可以在视图模型本身中进行此操作

    样本

        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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-23
      • 1970-01-01
      • 1970-01-01
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多