[英]Create DataGridRowsDetails in code behind WPF
我正在開發一個新程序,該程序將顯示有關工廠中某些工具的測試信息。 為此,我在運行時創建一個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"];
現在工作了一半。 我沒有資源方面的經驗,所以我找不到將數據綁定到它的解決方案。 我怎樣才能做到這一點?
謝謝您的幫助。
您可以將RowDetailsTemplate
屬性設置為使用XamlReader
類以編程方式創建的DataTemplate
,例如:
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;
我已經沿着這條線構建了一個通用的用戶控件,您可以在該控件上拋出任何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模式,這應該在視圖模型中嗎?)
我想我通過使用資源找到了解決方案:
<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"];
現在工作了一半。 我沒有資源方面的經驗,所以我找不到將數據綁定到它的解決方案。 我怎樣才能做到這一點?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.