WPF使用DataGrid数据绑定


前言

在这里插入图片描述


一、新建数据模型

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

/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
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
{
    /// <summary>
    /// DB_DataGrid.xaml 的交互逻辑
    /// </summary>
    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;
        }        
    }
}
 
  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BeanGo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值