如何使用最近4个月的名称填充C#ComboBox?

问题描述

| 我想使用C#在ComboBox显示最近4个月的名称。当用户选择一个月时,我需要将日期/时间传递给查询。使用日期/时间作为值时,如何显示月份名称?     

解决方法

        将组合框与by0ѭ和
ValueMember = theDateTime
绑定
ListItemCollection items = new ListItemCollection();
DateTime now = DateTime.Now;
for (int count = 1; count <= 4; count++)
{
    items.Add(new ListItem(now.ToString(\"MMM\"),now.ToString()));
    now.AddMonths(-1);
}
combobox.DisplayMember = \"Text\";
combobox1.ValueMember = \"Value\";
combobox1.DataSource = items;
然后获取用户选择的日期时间值
DateTime selected = Convert.ToDateTime(combobox1.SelectedValue);
    ,        您不会提供太多细节。我假设所选月份的值是一个整数。您可以创建一个虚拟的DateTime对象作为月值的占位符:
new DateTime(DateTime.Now.Year,selectedMonth,DateTime.Now.Day);
    ,         另一个想法是:下面的解决方案将实际的DateTime存储在列表中,而不是仅存储月份,例如2011年5月1日。当选择组合框时,输出实际上就是日期。 后面的代码:
    public MainWindow()
    {
        InitializeComponent();

        MyMonths = new List<DateTime>();
        var thisMonth = new DateTime(
            DateTime.Now.Year,DateTime.Now.Month,1);

        for (var i = 0; i < 4; i++)
        {
            MyMonths.Add(thisMonth.AddMonths(-i));
        }

        this.DataContext = this;
    }

    public List<DateTime> MyMonths
    {
        get { return (List<DateTime>)GetValue(MyMonthsProperty); }
        set { SetValue(MyMonthsProperty,value); }
    }
    public static readonly DependencyProperty MyMonthsProperty =
        DependencyProperty.Register(\"MyMonths\",typeof(List<DateTime>),typeof(MainWindow),new UIPropertyMetadata(null));      
Xaml:
    <StackPanel>
        <ComboBox x:Name=\"dateCombo\" 
                  Margin=\"10\"
                  SelectedIndex=\"0\"
                  ItemsSource=\"{Binding MyMonths}\">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text=\"{Binding Converter={StaticResource dateTimeConverter}}\"/>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
    </StackPanel>
DateTimeConverter:
public class DateTimeConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value,Type targetType,object parameter,System.Globalization.CultureInfo culture)
    {
        if (value is DateTime)
        {
            var d = (DateTime)value;
            return d.ToString(\"MMM\");
        }
        return string.Empty;
    }

    public object ConvertBack(object value,System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}
更新:格式化月份:
String.Format(\"{0:M MM MMM MMMM}\",dt);  // \"3 03 Mar March\"  month