【问题标题】:Binding ListView's GridView to List<KeyValuePair>将 ListView 的 GridView 绑定到 List<KeyValuePair>
【发布时间】:2016-01-10 18:29:14
【问题描述】:

这是我制作 GridView 的方式:

ListView 将包含Entry 对象,如下所示:

public class Entry
{
    public Entry(BitmapImage icon = null, List<EntryKeyValuePair> entryKeyValuePairs = null)
    {
        Icon = icon;
        EntryKeyValuePairs = entryKeyValuePairs ?? new List<EntryKeyValuePair>();
    }

    public BitmapImage Icon { get; set; }
    public List<EntryKeyValuePair> EntryKeyValuePairs { get; }
}

EntryKeyValuePair 只是一个KeyValuePair&lt;string,string&gt;,其中Key 是列,Value 是列的值。我使用了 KeyValuePair 列表,因为我想保留插入顺序。无论如何,这就是我构建 GridView 的方式。

GridView = new GridView();
foreach (Column column in Category.Columns.Where(c => c.IsVisibleInTable)) {
    var gridViewColumn = new GridViewColumn {
        Header = column.Name,
        DisplayMemberBinding = new Binding($"EntryKeyValuePairs[{column.Name}].Value")
    };
    GridView.Columns.Add(gridViewColumn);
}

我不知道在 DisplayMemberBinding 中设置什么绑定。如果EntryKeyValuePairs 是字典,则上述绑定将起作用。但就我而言,事实并非如此。

如果我能以某种方式访问​​数据对象,我可以这样做

DisplayMemberBinding = new Binding($"EntryKeyValuePairs[{entry.EntryKeyValuePairs.FindIndex(p => p.Key == column.Name)}].Value")

如何访问 ListView 在绑定时持有的当前数据对象?

【问题讨论】:

    标签: wpf gridview data-binding


    【解决方案1】:

    我找到了解决方案。我使用了GridViewColumn 的CellTemplateSelector,以便获得对ListViews 绑定对象的引用。这是CellTemplateSelector 的样子。我必须在代码中创建 DataTemplates。

    class GridViewCellTemplateSelector : DataTemplateSelector
    {
        private readonly string _columnName;
    
        public GridViewCellTemplateSelector(string columnName)
        {
            _columnName = columnName;
        }
    
        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            var entry = (Entry)item;
            var dataTemplate = new DataTemplate {
                DataType = typeof (Entry)
            };
    
            var stackPanelFactory = new FrameworkElementFactory(typeof(StackPanel));
            stackPanelFactory.SetValue(StackPanel.OrientationProperty, Orientation.Vertical);
    
            var text = new FrameworkElementFactory(typeof(TextBlock));
            text.SetBinding(TextBlock.TextProperty, new Binding($"EntryKeyValuePairs[{entry.EntryKeyValuePairs.FindIndex(p => p.Key == _columnName)}].Value"));
    
            stackPanelFactory.AppendChild(text);
    
            dataTemplate.VisualTree = stackPanelFactory;
    
            return dataTemplate;
        }
    }
    

    我使用了这个 TemplateSelector,而不是 DisplayMemberBinding:

    CellTemplateSelector = new GridViewCellTemplateSelector(column.Name)
    

    一切都好。希望这对某人有所帮助:) 我仍然希望看到比这更好的解决方案。

    【讨论】:

      猜你喜欢
      • 2010-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-16
      • 2011-02-10
      • 1970-01-01
      相关资源
      最近更新 更多