我在 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 MVVM Datagrid 是空的,但它不应该是
• 如何在鼠标悬停时为 DataGrid 行的背景颜色设置一次动画?
• WPF DatagridTemplateColumn 单元格单击事件仅在我单击单元格图标时才触发
• WPF - RowHeaderTemplate 在扩展时在控件顶部对齐
• 在 MudBlazor Datagrid 中放置 MudAutocomplete
• MUI DataGrid 过滤器服务器端 - 外部 API
• 在 Material UI 的 DataGrid 中的列上使用 renderCell 时,如何防止在组标题中呈现值?
• WinUI 3 DataGrid - 如何共享 DataGrid.Columns 定义
• Blazor Radzen DataGrid 自定义过滤未处理异常
• 在 DataGrid Material UI 中垂直滚动时列标题背景颜色发生变化
• 如何在 MUI datagrid checkboxSelection 中显示已选择的数据
• WPF Caliburn 微通知属性更改不更新 ShellView 中的 UI
• WPF MVVM Datagid with ComboBox column set ComboBox Background with alternate color