我使用MVVM 工具包和Material Design XAML 工具包
我的觀點:
我有一個資料網格:
<DataGrid AutoGenerateColumns="True" ItemsSource="{Binding Data}" AutoGeneratingColumn="DataGrid_AutoGeneratingColumn" />
我的視圖模型:
public partial class ViewModel: ObservableObject
{
[ObservableProperty]
DataTable _data;
public ViewModel()
{
var currentData = new DataTable();
currentData.Columns.Add("Name", typeof(string));
currentData.Columns.Add("BooleanValue", typeof(bool));
currentData.Columns.Add("Icon", typeof(PackIcon));
//Two rows
DataRow firstRow = currentData.NewRow();
DataRow secondRow = currentData.NewRow();
firstRow[0] = "Text1";
firstRow[1] = true;
firstRow[2] = new PackIcon { Kind = PackIconKind.SmileyHappy };
secondRow[0] = "Text2";
secondRow[1] = false;
secondRow[2] = new PackIcon { Kind = PackIconKind.SmileyAngry };
currentData.Rows.Add(firstRow);
currentData.Rows.Add(secondRow);
Data = currentData;
}
}
到目前為止,一切都很好。
DataGrid 顯示MaterialDesignThemes.Wpf.PackIcon而不是實際的圖示。我找到了非動態 DataGrid的解決方案,但這不適用于動態 DataGrid。
目標是特定單元格將顯示實際圖示。
由于我需要動態 DataGrid AutoGenerateColumns="True"。這個想法是我攔截 AutoGenerateColumns,每次型別為PackIcon時,我都會更改內容。
出于這個原因,我攔截它:
private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyType == typeof(PackIcon))
{
//todo
}
}
我嘗試了幾件事,但似乎不起作用。如何將“內容”設定為實際的 PackIcon 內容。我想,我可以做點什么,e.Column.CellStyle但我找不到將 a 轉換IconPack為 a 的方法Style。
提前致謝!
uj5u.com熱心網友回復:
如何將“內容”設定為實際的 PackIcon 內容。
您可以DataGridTemplateColumn使用 a創建一個ContentControl顯示圖示的:
private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyType == typeof(PackIcon))
{
const string Xaml = "<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">"
"<ContentControl Content=\"{{Binding {0}}}\" />"
"</DataTemplate>";
e.Column = new DataGridTemplateColumn()
{
Header = e.PropertyName,
CellTemplate = (DataTemplate)XamlReader.Parse(string.Format(Xaml, e.PropertyName))
};
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/527039.html
