wpf:DataGrid使用

             xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
             xmlns:WpfToolkit="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"

1.    WpfToolkit:DataGrid在TableView.xaml中定义如下

        <WpfToolkit:DataGrid  x:Name="PlotViewDataGrid" 
          ItemsSource="{Binding DataGridSource, Mode=TwoWay}"  IsReadOnly="True"  SelectedItem="{Binding DataGridSelected}"   
                              AutoGenerateColumns="True"   AutoGeneratedColumns="PlotViewDataGrid_AutoGeneratedColumns"  
                              Width="685"    RowHeight="25"  Margin="0"  CanUserResizeRows="True"  SelectionMode="Single"  
                              SelectedIndex="{Binding DataGridSelectedIndex, Mode=TwoWay}"  Grid.Row="0">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="SelectionChanged">
                    <i:InvokeCommandAction Command="{Binding GetSelectCommand}"
                                               CommandParameter="{Binding SelectedItem,ElementName=PlotViewDataGrid}" />
                </i:EventTrigger>
                <i:EventTrigger EventName="MouseDoubleClick">
                    <i:InvokeCommandAction Command="{Binding DataGridDoubleClickCommand}"
                                               CommandParameter="{Binding SelectedItem,ElementName=PlotViewDataGrid}" />
                </i:EventTrigger>
            </i:Interaction.Triggers>
            <WpfToolkit:DataGrid.RowStyle>
                <Style TargetType="{x:Type WpfToolkit:DataGridRow}">
                    <Setter Property="Background" Value="Red" />
                </Style>
            </WpfToolkit:DataGrid.RowStyle>
        </WpfToolkit:DataGrid>

1.在TableView.xmal.cs文件中PlotViewDataGrid_AutoGeneratedColumns函数可以改变列宽

  private void PlotViewDataGrid_AutoGeneratedColumns(object sender, EventArgs e)         {

            double dgwidth = this.PlotViewDataGrid.Width;            

            int columnWidth = this.PlotViewDataGrid.Columns.Count;

            this.PlotViewDataGrid.HorizontalContentAlignment = (HorizontalAlignment)1;          

          for (int i = 0; i < this.PlotViewDataGrid.Columns.Count; i++)          

           {                

         this.PlotViewDataGrid.Columns[i].Width = new Microsoft.Windows.Controls.DataGridLength(dgwidth / columnWidth);            

           }      

   }

2.在TableViewModel.cs文件中

      #region DataGridDoubleClickCommand
        RelayCommand<object> dataGridDoubleClickCommand = null;
        public ICommand DataGridDoubleClickCommand
        {
            get
            {
                if (dataGridDoubleClickCommand == null)
                {
                    dataGridDoubleClickCommand = new RelayCommand<object>((p) => OnDataGridDoubleClickCommand(p), (p) => CanDataGridDoubleClickCommand(p));
                }

                return dataGridDoubleClickCommand;
            }
        }

        private bool CanDataGridDoubleClickCommand(object p)
        {
            return true;
        }

        private void OnDataGridDoubleClickCommand(object p)
        {
            DataGridDoubleClickHandle(p);
        }
        #endregion

3.DataGrid风格自定义
   <WpfToolkit:DataGrid.RowStyle>
                <Style TargetType="{x:Type WpfToolkit:DataGridRow}">
                    <Setter Property="Background" Value="Red" />
                </Style>
            </WpfToolkit:DataGrid.RowStyle>

4.CanUserResizeRows="True"允许用户调整行高

其他参考内容如下:

(1)自动生成列

<DataGrid AutoGenerateColumns="True" Name="datagrid" CanUserAddRows="False" MouseDoubleClick="datagrid_MouseDoubleClick"/>

2)取消自动生成列,手动绑定到相应字段

<DataGrid AutoGenerateColumns="False" Name="datagrid" CanUserAddRows="False" MouseDoubleClick="datagrid_MouseDoubleClick">

   
<DataGrid.Columns>

       
<DataGridTextColumn Header="编号" Binding="{Binding ID}"></DataGridTextColumn>

       
<DataGridTextColumn Header="公司" Binding="{Binding CompanyName}"></DataGridTextColumn>

       
<DataGridTextColumn Header="固定资产" Binding="{Binding FixedAssets}" Width ="*"></DataGridTextColumn>

   
</DataGrid.Columns>

</DataGrid>

最后一列设置Width ="*"是为了取消空白列。

(3)后台代码

privatevoid Window_Loaded(object sender, RoutedEventArgs e)

{

    datagrid.ItemsSource
= AccessDAL.OleDbHelper.ExecuteDataTable("SELECT * from Customers").DefaultView;



//双击DataGrid,显示相应信息
privatevoid datagrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)

{

    DataRowView row
= datagrid.SelectedItem as DataRowView;

    MessageBox.Show(row[
"id"].ToString());

}

 
//如果绑定到对象集合,如ObservableCollection<Employee>,代码如下:

 ObservableCollection<Employee> col;

public EmployeeManage()

{

    InitializeComponent();

    col
=new ObservableCollection<Employee>();

    col.Add(
new Employee() { Id =1, Name ="Jim", Salary =2500.50f });

    col.Add(
new Employee() { Id =2, Name ="John", Salary =2600.50f });

    datagrid.ItemsSource
= col;

}

 
privatevoid datagrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)

{

    Employee emp
=datagrid.SelectedItem as Employee;

    MessageBox.Show(emp.Id.ToString());

}

(4)删除选中的多行数据

privatevoid Delete_Click(object sender, RoutedEventArgs e)

{

   
for (int i = datagrid.SelectedItems.Count -1; i >=0; i--)

    {

        Good good
= datagrid.SelectedItems[i] as Good;

        goods.Remove(good);

    }

}
posted @ 2014-01-28 16:30  zzlp  阅读(1377)  评论(0编辑  收藏  举报