首页 > 代码库 > WPF combobox

WPF combobox

先写一个数据类Grade.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;

namespace ImgProWPF
{
    public class Grade
    {
        public string Name { set; get; }
    }
    public class GradeAdd:ObservableCollection<Grade>
    {
        public GradeAdd()
        {
            this.Add(new Grade { Name = "0" });
            this.Add(new Grade { Name = "0.5" });
            this.Add(new Grade { Name = "1" });
            this.Add(new Grade { Name = "2" });
            this.Add(new Grade { Name = "3" });
            this.Add(new Grade { Name = "4" });
            this.Add(new Grade { Name = "5" });
        }
    }
}

在MainWindow.xaml里调用

xmlns:local="clr-namespace:ImgProWPF"
 <Grid.Resources>        
       <local:GradeAdd x:Key="grade"/>
 </Grid.Resources>
<ComboBox x:Name="comPersonalGrade" Grid.Column="1" Grid.Row="12" SelectedItem="0" ItemsSource="{StaticResource grade}" DisplayMemberPath="Name"/>

以上为绑定里数据,可以看到内容

下面为获得选中的内容

            Grade gradeP = (Grade)comPersonalGrade.SelectedItem;
            string gradep = gradeP.Name.ToString();