【问题标题】:WPF DataGrid binding list of string as rowWPF DataGrid 将字符串列表绑定为行
【发布时间】:2012-10-30 15:11:43
【问题描述】:

我不想使用类属性进行绑定。

为什么它不起作用?我该如何解决这个问题。我得到空行。我还为 DataGrid 手动定义了列。

 private void Insert(IList<string> row, DataGrid dG)
        {
            ObservableCollection<IList<string>> data = dG.ItemsSource as ObservableCollection<IList<string>>;
            data.Add(row);
            dG.ItemsSource = data;
        }

【问题讨论】:

    标签: wpf binding datagrid


    【解决方案1】:

    首先,如果您使用方法直接访问 DataGrid 属性而不是使用数据绑定,那么您应该使用 DataGrid.Items 属性,而不是 DataGrid.ItemsSource。

    private void Insert(IList<string> row, DataGrid dG)
    {
        dG.Items.Add(row);
    }
    

    但无论如何您都会得到空行,因为 DataGrid 无法将行中的每个字符串与正确的列定义链接。

    我认为最好的方法是使用转换器:

    创建继承自 IValueConverter 的 RowIndexConverter 类,并使您的 Convert 方法如下所示:

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        int index = System.Convert.ToInt32(parameter);
        return (value as IList)[index];
    }
    

    为此,您必须在绑定到 IList 属性(如 DataGrid 的行)中使用它,并将索引作为 ConverterParameter 传递。 XAML 将是这样的:

    <Window x:Class="Test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:Test"
        Title="MainWindow" Height="350" Width="525">
        <Window.Resources>
            <local:RowIndexConverter x:Key="rowIndexConverter" />
        </Window.Resources>
        <Grid>
            <DataGrid x:Name="DataGrid">
                <DataGrid.Columns>
                    <DataGridTextColumn Binding="{Binding ., Converter={StaticResource rowIndexConverter}, ConverterParameter=0}" />
                    <DataGridTextColumn Binding="{Binding ., Converter={StaticResource rowIndexConverter}, ConverterParameter=1}" />
                </DataGrid.Columns>
            </DataGrid>
        </Grid>
    </Window>
    

    瞧!值显示出来。如果您想要更多列,您只需添加它们并增加 ConvertParameter。小心,如果行不够长,转换器会抛出异常!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-16
      • 1970-01-01
      • 2019-06-05
      • 2014-05-20
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      • 2021-08-26
      相关资源
      最近更新 更多