WPF使用DataGrid数据绑定

文章目录

  • 前言
  • 一、新建数据模型
  • 二、界面设计
  • 三、数据初始化
  • 四、WPF DataGrid.DataGridComboBoxColumn 数据绑定


前言

WPF使用DataGrid数据绑定_第1张图片


一、新建数据模型

public class NotifyPropertyObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propertyName)
    {
        if(PropertyChanged != null)
        {
            PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }


}
public class MyStudent: NotifyPropertyObject
{
    private int _Num;

    public int Num
    {
        get { return _Num; }
        set { _Num = value;
            OnPropertyChanged("Num");
        }
    }

    private bool _IsTest;

    public bool IsTest
    {
        get { return _IsTest; }
        set { _IsTest = value;
            OnPropertyChanged("IsTest");
        }
    }


    private string _Name;

    public string Name
    {
        get { return _Name; }
        set { _Name = value;
            OnPropertyChanged("Name");
        }
    }

    private int _Age;

    public int Age
    {
        get { return _Age; }
        set { _Age = value;
            OnPropertyChanged("Age");
        }
    }

    private double _Score;

    public double Score
    {
        get { return _Score; }
        set { _Score = value;
            OnPropertyChanged("Score");
        }
    }

    private string _State; 

    public string State
    {
        get { return _State; }
        set { _State = value;
            OnPropertyChanged("State");
        }
    }

}

二、界面设计

<Window x:Class="WPFBindingDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPFBindingDemo"
        mc:Ignorable="d"
        Title="MainWindow" Height="650" Width="800">
    	<Grid>
	        <Grid.Resources>
	            <!--Create list of enumeration values-->
	            <ObjectDataProvider x:Key="strList" 
	            ObjectType="{x:Type local:OSList}" 
	            MethodName="GetList"/>
	        </Grid.Resources>
	        <Grid.ColumnDefinitions>
	            <ColumnDefinition/>
	            <ColumnDefinition/>
	        </Grid.ColumnDefinitions>
	        <Grid.RowDefinitions>
	            <RowDefinition Height="auto"/>
	            <RowDefinition />
	        </Grid.RowDefinitions>
	        <Grid Grid.Column="1" Name="GridTable" Height="360" Background="Silver" Margin="2">
	            <Grid.RowDefinitions>	
	                <RowDefinition></RowDefinition>	
	                <RowDefinition></RowDefinition>	
	                <RowDefinition></RowDefinition>
	                <RowDefinition></RowDefinition>
	            </Grid.RowDefinitions>
	            <Grid.ColumnDefinitions>
	                <ColumnDefinition Width="130"></ColumnDefinition>
	                <ColumnDefinition Width="150"></ColumnDefinition>
	                <ColumnDefinition Width="20"></ColumnDefinition>
	            </Grid.ColumnDefinitions>
	            <Label Width="130" Height="25"  Grid.Row="0" Grid.Column="0"  Name="label1">TwoWay</Label>
	            <TextBox Width="150" Height="25"  Grid.Row="0" Grid.Column="1"  Name="textBox4" Text="{Binding ElementName=scrollBar1,Path=Value,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />
	            <Label Width="130" Height="25"  Grid.Row="1" Grid.Column="0"  Name="label2">OneWay</Label>	
	            <TextBox Width="150" Height="25"  Grid.Row="1" Grid.Column="1"   Name="textBox1" Text="{Binding ElementName=scrollBar1, Path=Value,Mode=OneWay}"/>	
	            <Label Width="130" Height="25"  Grid.Row="2" Grid.Column="0"  Name="label3">OneWayToSource</Label>	
	            <TextBox Width="150" Height="25"  Grid.Row="2" Grid.Column="1"   Name="textBox2" Text="{Binding ElementName=scrollBar1, Path=Value,Mode=OneWayToSource}" />	
	            <Label Width="130" Height="25"  Grid.Row="3" Grid.Column="0"  Name="label4">OneTime</Label> 	
	            <TextBox Width="150" Height="25"  Grid.Row="3" Grid.Column="1"   Name="textBox3" Text="{Binding ElementName=scrollBar1, Path=Value,Mode=OneTime}"/>
	            <ScrollBar Value="30" Minimum="0" Grid.RowSpan="4" Grid.Row="0" Grid.Column="3" Maximum="100" Name="scrollBar1" Width="18" Height="{Binding ElementName=GridTable,Path=Height}" />
	
        </Grid>

        <Grid Margin="2" Background="GreenYellow" Grid.Row="1" Grid.Column="1">
            <DataGrid x:Name="dataGridName" CanUserAddRows="False" AutoGenerateColumns="False" ItemsSource="{Binding MyStudentList,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" CanUserSortColumns="False">
                <DataGrid.Columns>
                    <DataGridCheckBoxColumn Header="选择" Width="*" Binding="{Binding IsTest}"></DataGridCheckBoxColumn>
                    <DataGridTextColumn Header="Num" Width="*" Binding="{Binding Num}"></DataGridTextColumn>
                    <DataGridTextColumn Header="Name" Width="*" Binding="{Binding Name}"></DataGridTextColumn>
                    <DataGridTextColumn Header="Age" Width="*" Binding="{Binding Age}"></DataGridTextColumn>
                    <DataGridTextColumn Header="Score" Width="*" Binding="{Binding Score}"></DataGridTextColumn>
                    <DataGridComboBoxColumn Header="State" Width="*" ItemsSource="{Binding Source={StaticResource strList}}" SelectedItemBinding="{Binding State}" TextBinding="{Binding State,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
                    </DataGridComboBoxColumn>
                    <DataGridComboBoxColumn Header="State" Width="*" ItemsSource="{x:Static local:StrList.StateList}" SelectedItemBinding="{Binding State}" TextBinding="{Binding State,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
                    </DataGridComboBoxColumn>
                   
                    <!--<DataGridTemplateColumn Header="Image" Width="SizeToCells" IsReadOnly="True">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Image Source="{Binding Image}" />
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>-->
                </DataGrid.Columns>
            </DataGrid>
        </Grid>
    </Grid>
</Window>
        

三、数据初始化

public class OSList
{
   string[] txList = new string[] { "1", "2", "3" };

   public string[] GetList()
   {
       return this.txList;
   }
}

public class StrList
{
   public static List<string> StateList { get; set; }

   static StrList()
   {
       StateList = new List<string>() { "1", "2", "3","4" };
   }
}

/// 
/// MainWindow.xaml 的交互逻辑
/// 
public partial class MainWindow : Window
{
   public ViewModels.MainViewModel ViewModel { get { return App.MainViewModel; } }

   public List<MyStudent> MyStudentList = new List<MyStudent>();

   public MainWindow()
   {
       InitializeComponent();

       this.DataContext = ViewModel;

       this.Loaded += MainWindow_Loaded;
   }

   private void MainWindow_Loaded(object sender, RoutedEventArgs e)
   {
       MyStudentList = new List<MyStudent>();

       for (int i = 0; i < 5; i++)
       {
           MyStudent myStudent = new MyStudent();
           myStudent.Num = i+1;
           myStudent.IsTest = true;
           myStudent.Name = "d" + i.ToString();
           myStudent.Age = i + 12;
           myStudent.Score = i + 78;
           myStudent.State = "1";
           MyStudentList.Add(myStudent);
       }

       dataGridName.ItemsSource = null;
       dataGridName.ItemsSource = MyStudentList;

   }

}

四、WPF DataGrid.DataGridComboBoxColumn 数据绑定

xaml代码:

<Grid>
    <Grid.Resources>
        <!--Create list of enumeration values-->
        <ObjectDataProvider x:Key="strList" 
            ObjectType="{x:Type local:OSList}" 
            MethodName="GetList"/>
    </Grid.Resources>
    <DataGrid Name="DG1" ItemsSource="{Binding}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridComboBoxColumn Header="下拉框测试"
               SelectedItemBinding="{Binding sIdx}" ItemsSource="{Binding Source={StaticResource strList}}">
            </DataGridComboBoxColumn>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

逻辑代码:

namespace DataBingTest
{
    /// 
    /// DB_DataGrid.xaml 的交互逻辑
    /// 
    public partial class DB_DataGrid : Window
    {
        public DB_DataGrid()
        {
            InitializeComponent();
 
            List<Info> infoList = new List<Info>();
 
            Info info02 = new Info();
            info02.sIdx = "1";
            infoList.Add(info02);
            info02 = new Info();
            info02.sIdx = "2";
            infoList.Add(info02);
            info02 = new Info();
            info02.sIdx = "3";
            infoList.Add(info02);
 
            DG1.DataContext = infoList;
        }
    }
 
    public class Info
    {
        public string sIdx { get; set; }
    }
 
    public class OSList
    {
        string[] txList = new string[] {"1" ,"2","3"};
 
        public string[] GetList()
        {
            return this.txList;
        }        
    }
}
 

你可能感兴趣的:(WPF,开发语言,c#,wpf)