为每个项目应用转换器 WPF DataGrid

问题描述 投票:0回答:0

我在 WPF 应用程序中有一个 DataGrid。此数据网格的项目源是由不同类型的对象组成的列表。我还有一个转换器,可以将所有不同源类型的对象按照一定的规则转换成一个匿名对象。是否可以将 xaml 转换器应用于 itemssource 的每个元素?

这是我的代码:

 public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            
            List<object> dataSource = new List<object>()
            {
                new BvFile { Name = "file1", Size = 200 },
                new BvFolder { Name = "folder"}
            };

            //lbox.ItemsSource = dataSource;
            dGridTest.ItemsSource = dataSource;
            var bp = 0;
        }
    }

    class BvFolder
    {
        public string Name { get; set; }
    }

    class BvFile
    {
        public string Name { get; set; }
        public int Size { get; set; }
    }

    public class BvElementConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string nameValue = null;
            string sizeValue = null;
            if (value is BvFile)
            {
                BvFile file = value as BvFile;
                nameValue = file.Name;
                sizeValue = file.Size.ToString();
            }

            if (value is BvFolder)
            {
                BvFolder file = value as BvFolder;
                nameValue = file.Name;
                sizeValue = "this is folder";
            }

            return
                new
                {
                    Name = nameValue,
                    Size = sizeValue
                };
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }
    }

XAML:

            <GridSplitter></GridSplitter>
            <DataGrid x:Name="dGridTest" AutoGenerateColumns="False">                
                <DataGrid.Columns>                    
                    <DataGridTextColumn Binding="{Binding Name}"
                                        Header="Наименование"/>
                    <DataGridTextColumn Binding="{Binding Size}"
                                        Header="Размер"/>
                </DataGrid.Columns>
            </DataGrid>

我试过:

                <DataGrid.ItemContainerStyle>
                    <Style TargetType="{x:Type DataGridRow}">
                        <Setter Property="DataContext"
                                Value="{Binding Path=DataContext,                            
                            RelativeSource={RelativeSource Self},
                            Converter={StaticResource ElementConverter}}">                            
                        </Setter>                       
                    </Style>
                </DataGrid.ItemContainerStyle> 

预计: 每个数据行都会得到转换后的项目

wpf datagrid
© www.soinside.com 2019 - 2024. All rights reserved.