【问题标题】:Data value in the wpf grid is not getting right and center alignedwpf 网格中的数据值未正确且居中对齐
【发布时间】:2014-03-20 05:53:34
【问题描述】:

我正在使用 wpf 数据网格。我希望数据在网格中正确并居中对齐。目前我正在使用 Style setter 属性,但没有任何东西对我有用

private void DgvInvoice_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {

                    DataGridColumn nextColumn = DgvInvoice.ColumnFromDisplayIndex(7); // Display Index 7 is Amount Colum in the grid 

                    DataGridRow row = (DataGridRow)DgvInvoice.ItemContainerGenerator.ContainerFromItem(new DataGridCellInfo(DgvInvoice.SelectedItem, nextColumn).Item);

                    DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);

                    DataGridCell gridCell = presenter.ItemContainerGenerator.ContainerFromIndex(7) as DataGridCell;
                    if (gridCell != null)
                    {

                        if (d != 0)
                        {
                            gridCell.Content = String.Format("{0:#,0}", d);
                        }
                        else { gridCell.Content = string.Empty; }

                        Style s = new Style();
                        gridCell.Height = 29;
                        s.Setters.Add(new Setter(TextBox.TextAlignmentProperty, TextAlignment.Right));
                        s.Setters.Add(new Setter(TextBox.VerticalContentAlignmentProperty, VerticalAlignment.Center));
                        gridCell.Style = s;
                    }
                }

【问题讨论】:

    标签: wpf c#-4.0 wpfdatagrid


    【解决方案1】:

    试试这个,

    Style alignStyle = new Style(typeof(DataGridCell));
    alignStyle.Setters.Add(new  Setter(DataGridCell.WidthProperty, 20.0));
    alignStyle.Setters.Add(new Setter(DataGridCell.HorizontalAlignmentProperty,HorizontalAlignment.Center));
    alignStyle.Setters.Add(new  Setter(DataGridCell.VerticalAlignmentProperty,VerticalAlignment.Center));
    YouDataGridName.Style = alignStyle; 
    

    【讨论】:

      【解决方案2】:

      我只是为你准备了 xaml 样式

          <Style x:Key="GridCellStyle" TargetType="{x:Type TextBlock}">
              <Setter Property="HorizontalAlignment" Value="Right" />
              <Setter Property="VerticalAlignment" Value="Right" />
          </Style>
      
       <DataGridTextColumn Header="Betrag" MinWidth="125"
                      Binding="{Binding Path=Betrag, Mode=OneWay, StringFormat=#\,##0.00}"
                      ElementStyle="{StaticResource GridCellStyle}" />
      

      【讨论】:

        【解决方案3】:

        注意:这里的标题要求“Grid”,它不同于“DataGrid”。

        【讨论】:

          猜你喜欢
          • 2016-05-25
          • 2018-04-08
          • 1970-01-01
          • 2019-01-17
          • 1970-01-01
          • 1970-01-01
          • 2011-10-10
          相关资源
          最近更新 更多