wpf 用月份和月份数字填充组合框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15860954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:30:37  来源:igfitidea点击:

Filling a combobox with Months and numbers for months

c#wpfcombobox

提问by AbdulAziz

I am working on a WPF project and I have a months combobox that should contain months from Jan to Dec. I managed to do it by following snippet;

我正在处理一个 WPF 项目,我有一个包含从 1 月到 12 月的几个月的组合框。我设法通过以下代码段做到了;

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

And got the list as;

并得到名单;

January
February
March
....

But I want them to populate as ;

但我希望它们填充为 ;

01 - January
02 - February
03 - March
.....

Any ideas how proceed it with for loop? I am newbie to C#. Thanks

任何想法如何进行 for 循环?我是 C# 的新手。谢谢

回答by user892381

Noo. Why are you doing it in the backend. Take advantage of wpf and use the xaml.

不。你为什么要在后台做。利用 wpf 并使用 xaml。

Let me try to explain how to do this.

让我试着解释一下如何做到这一点。

  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.htmlif 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>
    
  1. 首先为 Months 创建一个依赖属性。如果您还没有使用依赖属性。你现在应该研究它们http://wpftutorial.net/DependencyProperties.html。在下面的代码中,我通过 new PropertyMetadata(new CultureInfo("en-US").DateTimeFormat.MonthNames.Take(12).ToList()) 将属性的默认值设置为月份列表。所以现在我们可以从 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. 你需要一个转换器。 http://wpftutorial.net/ValueConverters.html如果不熟悉它们。转换器要做的是对列表中的每个值我们要修改字符串以获得所需的结果。因此,为值转换器创建一个新类。

    [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. 在 xaml 中设置它。为您的窗口创建一个名称,即 x:Name="testWindow",这样可以在绑定时更好地访问它。设置您的命名空间,以便您可以获得转换器。xmlns:Main="clr-namespace:WpfApplication4"。将转换器添加到资源中。在组合框中将 itemssource 绑定到您的依赖属性 Months 并通过转换器发送它。

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

回答by Thousand

      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++;
      }

回答by KF2

Try this:

尝试这个:

   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);

回答by fvempy

The best way to do it would be to have a combo box for the day and combo box for the month.

最好的方法是有一个当天的组合框和一个月的组合框。

Populating month and day

填充月和日

uses

用途

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