用月份和数字填充下拉框的方法

4

我正在进行一个WPF项目,我有一个月份下拉框,应该包含一月到十二月。我通过以下代码片段来实现它:

var americanCulture = new CultureInfo("en-US");
ddlMonth.Items.AddRange(americanCulture.DateTimeFormat.MonthNames);

并获得以下列表:

January
February
March
....

但是我希望它们能够填充为;
01 - January
02 - February
03 - March
.....

有什么想法如何使用for循环处理它?我是C#的新手。谢谢。

你真的想显示月份数字,还是想显示“四月”并使所选值为“4”? - Corak
不,我想要显示月份号码和月份名称。 - AbdulAziz
4个回答

5
      var americanCulture = new CultureInfo("en-US");
      var count = 1;
      //.Take(12) in the foreach below because apparantly MonthNames returns 13
      //elements of which the last one is empty
      foreach (var month in americanCulture.DateTimeFormat.MonthNames.Take(12))
      {    
      DropDownList1.Items.Add(new ListItem{Text = count.ToString("00") + "-" + month});
      count++;
      }

1
count.ToString("00") + " - " + month - Corak

5

不要这样在后端做,请利用WPF并使用XAML。

让我尝试解释如何实现。

  1. First create a dependency property for the Months. If you haven't used dependency properties. You should research them now http://wpftutorial.net/DependencyProperties.html. In below code I am setting the default value of the property to a list of the months via new PropertyMetadata(new CultureInfo("en-US").DateTimeFormat.MonthNames.Take(12).ToList())). So now we can obtain this property from the xaml.

    public partial class MainWindow : Window
    {
    public static readonly DependencyProperty MonthsProperty = DependencyProperty.Register(
        "Months", 
        typeof(List<string>), 
        typeof(MainWindow), 
        new PropertyMetadata(new CultureInfo("en-US").DateTimeFormat.MonthNames.Take(12).ToList()));
    
    public List<string> Months
    {
        get
        {
            return (List<string>)this.GetValue(MonthsProperty);
        }
    
        set
        {
            this.SetValue(MonthsProperty, value);
        }
    }
    public MainWindow()
    {
        InitializeComponent();            
    }
    

    }

  2. You need a converter. http://wpftutorial.net/ValueConverters.html if not familiar with them. What the converter is going to do is for every value in the list we are going to modify the string to get the desired result you want. So create a new class for the value converter.

    [ValueConversion(typeof(List<string>), typeof(List<string>))]
    public class MonthConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
        //get the list of months from the object sent in    
        List<string> months = (List<string>)value;
    
        //manipulate the data index starts at 0 so add 1 and set to 2 decimal places
        if (months != null && months.Count > 0)
        {
            for (int x = 0; x < months.Count; x++)
            {
                months[x] = (x + 1).ToString("D2") + " - " + months[x];
            }
        }
    
        return months;
    }
    
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
    
    #endregion
    

    }

  3. Set it up in the xaml. Create a name for your window ie x:Name="testWindow", this is so can better access it when binding. Setup your namespace so you can get the converter. xmlns:Main="clr-namespace:WpfApplication4". Add the converter to the resources, . In the combobox bind the itemssource to your dependency property Months and send it through the converter.

    <Window x:Class="WpfApplication4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Name="testwindow"
        xmlns:Main="clr-namespace:WpfApplication4"
        Title="MainWindow" Height="350" Width="525">
    
        <Window.Resources>
            <Main:MonthConverter x:Key="MonthConverter"/>
        </Window.Resources>
    
        <Grid>
            <ComboBox ItemsSource="{Binding ElementName=testwindow,Path=Months, Converter={StaticResource MonthConverter}}" HorizontalAlignment="Left" Margin="197,107,0,0" VerticalAlignment="Top" Width="120"/>
    
        </Grid>
    </Window>
    

你还应该在组合框上设置默认选择,<ComboBox SelectedIndex="0"... 或者其他什么。 - user892381
抱歉,我没有看到你是C#新手,所以这可能有点困难。我使用的是WPF必备知识,包括依赖属性、绑定和值转换器。wpftutorial.net对学习基础知识非常有帮助。 - user892381

2

试试这个:

   List<string> names = new List<string>();
        int num = 1;
        foreach (var item in americanCulture.DateTimeFormat.MonthNames)
        {
            names.Add(string.Format("{0} - {1}", num++.ToString("D2"), item));
        }
        ddlMonth.Items.AddRange(names);

在此代码之前添加:var americanCulture = new CultureInfo("en-US"); - moksef

2

最好的方法是为日期和月份分别设置下拉框。

填充月份和日期

用法:

for (int i = 1; i <= DateTime.DaysInMonth(year, month); i++) {
    cmbDay.Items.Add(i.ToString());
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接