首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C# WPF DataGrid AutoGeneratingColumn PackIcon内容

C# WPF DataGrid AutoGeneratingColumn PackIcon内容
EN

Stack Overflow用户
提问于 2022-10-30 09:52:05
回答 1查看 31关注 0票数 1

我使用MVVM工具包材料设计XAML工具包

我的观点:

我有个数据格力:

代码语言:javascript
复制
<DataGrid AutoGenerateColumns="True" ItemsSource="{Binding Data}" AutoGeneratingColumn="DataGrid_AutoGeneratingColumn" />

我的ViewModel:

代码语言:javascript
复制
    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时,我都会更改内容。

出于这个原因,我拦截它:

代码语言:javascript
复制
 private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            if (e.PropertyType == typeof(PackIcon))
            {
                //todo 
            }
        }

我试过几样东西,但似乎不管用。如何将“内容”设置为实际的PackIcon内容。我想,我可以用e.Column.CellStyle做点什么,但我找不到办法将IconPack转换成Style

提前感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-31 15:49:55

如何将“内容”设置为实际的PackIcon内容。

您可以使用显示图标的DataGridTemplateColumn创建一个ContentControl

代码语言:javascript
复制
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))
        };
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74252029

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档