在WPF后面的代码中创建DataGridRowsDetails

时间:2017-07-11 07:30:01

标签: c# wpf

我正在开发一个新程序,它将在我工厂的某些工具上显示有关Test的信息。 为此,我在运行时创建一个DataGrid控件并填充它。这部分工作得非常好。

我的问题是添加RowDetails,我怎么能在代码背后做到这一点?

if (datatable.Rows.Count != 0)
    {
      foreach (DataRow dt in datatable.Rows)
        {
          if (last_tool_test == "" || last_tool_test != dt[1].ToString())
             {
               last_tool_test = dt[1].ToString();
               txt = new TextBlock();
               txt.Text = dt[1].ToString() + " :";
               txt.TextDecorations = TextDecorations.Underline;
               txt.HorizontalAlignment = HorizontalAlignment.Center;
               txt.Margin = new Thickness(0, 0, 0, 7);

               data = new DataGrid();
               data.Width = double.NaN;
               data.Margin = new Thickness(5, 0, 5, 5);
               data.HeadersVisibility = DataGridHeadersVisibility.Column;
               data.CanUserAddRows = false;
               data.CanUserDeleteRows = false;
               data.CanUserReorderColumns = false;
               data.CanUserResizeColumns = false;
               data.CanUserSortColumns = false;
               data.IsReadOnly = true;
               data.SelectionMode = DataGridSelectionMode.Extended;
               DataGridTextColumn col1 = new DataGridTextColumn();
               col1.Header = "Recipe Name";
               col1.Binding = new Binding("Recipe_Name");
               col1.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
               var style = new Style(typeof(DataGridColumnHeader));
               style.Setters.Add(new Setter()
               {
                Property = HorizontalAlignmentProperty,
                Value = HorizontalAlignment.Stretch
               });
               style.Setters.Add(new Setter()
               {
                Property = HorizontalContentAlignmentProperty,
                Value = HorizontalAlignment.Center
               });
               style.Setters.Add(new Setter()
               {
                Property = FontWeightProperty,
                Value = FontWeights.Bold
               });
               var style1 = new Style(typeof(TextBlock));
               style1.Setters.Add(new Setter()
               {
                Property = HorizontalAlignmentProperty,
                Value = HorizontalAlignment.Center
               });
               col1.HeaderStyle = style;
               col1.ElementStyle = style1;
               data.Columns.Add(col1);
               DataGridTextColumn col2 = new DataGridTextColumn();
               col2.Header = "Foup";
               col2.Width = 100;
               col2.Binding = new Binding("Foup");
               col2.HeaderStyle = style;
               col2.ElementStyle = style1;
               data.Columns.Add(col2);
               DataGridTextColumn col3 = new DataGridTextColumn();
               col3.Header = "Need Reference?";
               col3.Width = 110;
               col3.HeaderStyle = style;
               col3.ElementStyle = style1;
               col3.Binding = new Binding("Reference");
               data.Columns.Add(col3);
               DataGridTextColumn col4 = new DataGridTextColumn();
               col4.Header = "# Iteration";
               col4.Width = 100;
               col4.HeaderStyle = style;
               col4.ElementStyle = style1;
               col4.Binding = new Binding("Iteration");
               data.Columns.Add(col4);
               DataGridTextColumn col5 = new DataGridTextColumn();
               col5.Header = "Spec";
               col5.Width = 100;
               col5.HeaderStyle = style;
               col5.ElementStyle = style1;
               data.Columns.Add(col5);
               col5.Binding = new Binding("Spec");
               st.Children.Add(txt);
               st.Children.Add(data);
             }                                    
            data.Items.Add(new Tool_Test() { Recipe_Name = dt[2].ToString(), Foup = dt[3].ToString(), Reference = dt[4].ToString(), Iteration = dt[5].ToString(), Spec = dt[6].ToString() });
        }
        last_tool_test = "";
      }
   }

编辑:我想我通过资源找到了解决方案:

<Window.Resources>
    <DataTemplate x:Key="CustomTemplate">
        <DataGrid x:Name="datagrid1" HeadersVisibility="Column" CanUserAddRows="False" CanUserDeleteRows="False" CanUserResizeRows="False" SelectionMode="Extended" Margin="5,0,5,50" CanUserResizeColumns="False" AutoGenerateColumns="False" VerticalAlignment="Top" IsReadOnly="True" Width="750">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Sub Test Name" Width="*" Binding="{Binding Path=Recipe_Name}">
                    <DataGridTextColumn.HeaderStyle>
                        <Style TargetType="DataGridColumnHeader">
                            <Setter Property="HorizontalAlignment" Value="Stretch"/>
                            <Setter Property="HorizontalContentAlignment" Value="Center"/>
                            <Setter Property="FontWeight"  Value="Bold" />
                        </Style>
                    </DataGridTextColumn.HeaderStyle>
                    <DataGridTextColumn.ElementStyle>
                        <Style TargetType="TextBlock">
                            <Setter Property="HorizontalAlignment" Value="Center" />
                        </Style>
                    </DataGridTextColumn.ElementStyle>
                </DataGridTextColumn>
                <DataGridTextColumn Header="Spec" Width="*" Binding="{Binding Path=Foup}">
                    <DataGridTextColumn.HeaderStyle>
                        <Style TargetType="DataGridColumnHeader">
                            <Setter Property="HorizontalAlignment" Value="Stretch"/>
                            <Setter Property="HorizontalContentAlignment" Value="Center"/>
                            <Setter Property="FontWeight"  Value="Bold" />
                        </Style>
                    </DataGridTextColumn.HeaderStyle>
                    <DataGridTextColumn.ElementStyle>
                        <Style TargetType="TextBlock">
                            <Setter Property="HorizontalAlignment" Value="Center" />
                        </Style>
                    </DataGridTextColumn.ElementStyle>
                </DataGridTextColumn>
            </DataGrid.Columns>
        </DataGrid>
    </DataTemplate>
</Window.Resources>

在我的代码中我添加了这个:

data.RowDetailsTemplate = (DataTemplate)this.Resources["CustomTemplate"];

现在它已经完成了一半。我没有资源经验,所以我找不到将数据绑定到它的解决方案。我怎么能这样做?

感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

您可以将RowDetailsTemplate属性设置为使用DataTemplate类以编程方式创建的XamlReader,例如:

string template = "<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\"><TextBlock Text=\"some text...\"></DataTemplate>";
data.RowDetailsTemplate = XamlReader.Parse(template) as DataTemplate;

答案 1 :(得分:0)

我已经在这些行中构建了一个通用的用户控件,您可以在其中抛出任何ObservableCollection对象,它将构建表,但是您想要定义标题列宽等等。所以它不仅仅使用标题和默认宽度的函数名称。

首先,我创建了一个对象来保存每列的设置:

    public DataGridColumnSettings(string Header, int ColumnIndex, bool IsReadOnly = true, string Width = "100", bool ComboBoxColumn = false, bool CheckBoxColumn = false)
    {
        this.Header = Header;
        this.ColumnIndex = ColumnIndex;
        this.IsReadOnly = IsReadOnly;
        this.Width = Width;
        this.ComboBoxColumn = ComboBoxColumn;
        this.CheckBoxColumn = CheckBoxColumn;
    }

然后我为每个模型制作了这些模型的集合(我使用的是MVVM模式):

        public static Dictionary<string, DataGridColumnSettings> ColumnSettings
        {
            get { return new Dictionary<string, DataGridColumnSettings>() { { "PurchaseOrder", new DataGridColumnSettings("Order Number", 0) }, { "Width", new DataGridColumnSettings("Width", 1) }, { "Length", new DataGridColumnSettings("Length", 2) }, { "NumberOfPallets", new DataGridColumnSettings("No of Pallets", 3) }, { "BoardsPerStack", new DataGridColumnSettings("No of Boards", 4) }, { "NumberOfBoards", new DataGridColumnSettings("Total Boards", 5) } }; ; }
        }

字典键是模型中用于表行中所需值的get set方法(默认情况下将调用这些列)

并在创建视图对象(UserControl)时传入此字典并将其存储在View:

 v_DataTable View = new v_DataTable(Model.ColumnSettings);

现在为数据网格自动生成列事件添加处理程序:

<DataGrid AutoGeneratingColumn="dataGrid_AutoGeneratingColumn" />(xaml)

并将处理程序添加到后面的代码中:

private void dataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    string headername = e.Column.Header.ToString();

    //// Any column not in header details is a hidden column
    if (this.headerDetails.ContainsKey(headername))
    {
        Style centerStyle = new Style { TargetType = typeof(DataGridCell) };
        centerStyle.Setters.Add(new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Center));
        Style headerCenterStyle = new Style { TargetType = typeof(DataGridColumnHeader) };
        headerCenterStyle.Setters.Add(new Setter(HorizontalContentAlignmentProperty, HorizontalAlignment.Center));


        try
        {
            e.Column.Width = Double.Parse(this.headerDetails[headername].Width);
        }
        catch(Exception ex)
        {
                e.Column.Width = 100;
        }

        // You can also add bindings here if required
        Binding headerTextBinding = new Binding();
        headerTextBinding.Source = this.headerDetails[headername];
        headerTextBinding.Path = new PropertyPath("Header");
        headerTextBinding.Mode = BindingMode.TwoWay;
        headerTextBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
        BindingOperations.SetBinding(e.Column, DataGridTextColumn.HeaderProperty, headerTextBinding);


        e.Column.HeaderStyle = headerCenterStyle;
        e.Column.DisplayIndex = this.headerDetails[headername].ColumnIndex; //// If you have issues with the index been out of range, change the order of the get/set functions in the model class
        e.Column.CellStyle = centerStyle;                                   //// putting the get/set for any fields that are not displayed first will also help to avoid the issue
        e.Column.IsReadOnly = this.headerDetails[headername].IsReadOnly;
    }
    else
    {
        e.Column.Visibility = Visibility.Hidden;
    }
}

在这里,您可以使用传入的设置根据需要自定义列。 (如果遵循MVVM模式,它应该在View Model中吗?)

答案 2 :(得分:0)

我认为我使用资源找到了解决方案:

<Window.Resources>
<DataTemplate x:Key="CustomTemplate">
    <DataGrid x:Name="datagrid1" HeadersVisibility="Column" CanUserAddRows="False" CanUserDeleteRows="False" CanUserResizeRows="False" SelectionMode="Extended" Margin="5,0,5,50" CanUserResizeColumns="False" AutoGenerateColumns="False" VerticalAlignment="Top" IsReadOnly="True" Width="750">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Sub Test Name" Width="*" Binding="{Binding Path=Recipe_Name}">
                <DataGridTextColumn.HeaderStyle>
                    <Style TargetType="DataGridColumnHeader">
                        <Setter Property="HorizontalAlignment" Value="Stretch"/>
                        <Setter Property="HorizontalContentAlignment" Value="Center"/>
                        <Setter Property="FontWeight"  Value="Bold" />
                    </Style>
                </DataGridTextColumn.HeaderStyle>
                <DataGridTextColumn.ElementStyle>
                    <Style TargetType="TextBlock">
                        <Setter Property="HorizontalAlignment" Value="Center" />
                    </Style>
                </DataGridTextColumn.ElementStyle>
            </DataGridTextColumn>
            <DataGridTextColumn Header="Spec" Width="*" Binding="{Binding Path=Foup}">
                <DataGridTextColumn.HeaderStyle>
                    <Style TargetType="DataGridColumnHeader">
                        <Setter Property="HorizontalAlignment" Value="Stretch"/>
                        <Setter Property="HorizontalContentAlignment" Value="Center"/>
                        <Setter Property="FontWeight"  Value="Bold" />
                    </Style>
                </DataGridTextColumn.HeaderStyle>
                <DataGridTextColumn.ElementStyle>
                    <Style TargetType="TextBlock">
                        <Setter Property="HorizontalAlignment" Value="Center" />
                    </Style>
                </DataGridTextColumn.ElementStyle>
            </DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>
</DataTemplate>

在我的代码中我添加了这个:

data.RowDetailsTemplate = (DataTemplate)this.Resources["CustomTemplate"];

现在它已经完成了一半。我没有资源经验,所以我找不到将数据绑定到它的解决方案。我怎么能这样做?