欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

WPF 精修篇 DataGrid 数据源排序

程序员文章站 2024-02-16 12:29:28
...

效果

WPF 精修篇 DataGrid 数据源排序

        <DataGrid x:Name="datagrid" ItemsSource="{Binding ElementName=Mwindow, Path=Preson}" Margin="0,0,0,20">
            <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Name}" Header="Name"></DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding Address}" Header="Address"></DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding Age}" Header="Age"></DataGridTextColumn>
            </DataGrid.Columns>
        </DataGrid>
        <CheckBox x:Name="sort" Content="排序" HorizontalAlignment="Left" Margin="466,300,0,0" VerticalAlignment="Top" Checked="CheckBox_Checked"/>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            
                Preson = new ObservableCollection<Preson>() { 
                new Preson() { Name = "慧哥1", Address = "大连1", Age = 31 },
                new Preson() { Name = "慧哥2", Address = "大连2", Age = 32 },
                new Preson() { Name = "慧哥3", Address = "大连3", Age = 33 },
                new Preson() { Name = "慧哥4", Address = "大连4", Age = 34 },
                new Preson() { Name = "慧哥5", Address = "大连5", Age = 35 },
                new Preson() { Name = "123", Address = "大连6", Age = 12 },
                new Preson() { Name = "444", Address = "大连7", Age = 14 },
                new Preson() { Name = "222", Address = "大连8", Age = 33 },
                new Preson() { Name = "1312", Address = "大连9", Age = 22 }
            };
        

          
        }



        public ObservableCollection<Preson> Preson
        {
            get { return (ObservableCollection<Preson>)GetValue(PresonProperty); }
            set { SetValue(PresonProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Preson.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty PresonProperty =
            DependencyProperty.Register("Preson", typeof(ObservableCollection<Preson>), typeof(MainWindow), new PropertyMetadata(null));

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            var cvs = CollectionViewSource.GetDefaultView(datagrid.ItemsSource);
            if(cvs!=null&&cvs.CanSort)
            {
                cvs.SortDescriptions.Clear();
                if (sort.IsChecked == true)
                {
                    cvs.SortDescriptions.Add(new System.ComponentModel.SortDescription("Age", System.ComponentModel.ListSortDirection.Descending));
                }
              
            }
        }

        

 

        
    }

 

留作记录

 

相关标签: WPF

上一篇: WPF 精修篇 page

下一篇: