【问题标题】:WPF: Custom collection ( List<Type>) databinding to a Listbox with Path filteringWPF:自定义集合 (List<Type>) 数据绑定到具有路径过滤的列表框
【发布时间】:2017-03-04 20:37:43
【问题描述】:

我创建了一个自定义 DataSourceProvider,它提供了一个 List&lt;XmlNode&gt; 作为查询结果。

通过使用 Path 参数,生成的 Listbox 应该包含在 XmlNode 中命名的属性的指定列表

Path=Tag 应使用列表中包含的标记填充列表框。但它使用第一个 List-items 标记填充列表。

问题是为什么 Path 参数不检索 List 中的所有 Tag 元素,而只检索第一个列表元素 Tag 中的字母。



自定义列表作为资源提供:

<Window.Resources>

    <classes:Custom_XmlProvider x:Key="txtProvider" Path="name" />

</Window.Resources>

ListBox 使用 Path=Tag 绑定到资源:

 <ListBox Grid.Row="1" ItemsSource="{Binding Path=Tag, Source={ StaticResource txtProvider}}"
             DockPanel.Dock="Bottom">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Label Content="{Binding}" FontFamily="Arial" FontWeight="Normal" Margin="5,0,0,0"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

自定义 DataSourceProvider 返回包​​含 1200 个对象的 List:

protected override void BeginQuery()
    {
        System.Threading.ThreadPool.QueueUserWorkItem(RunQuery, null);
    }

    private void RunQuery(object state)
    {
        base.BeginQuery();

        try
        {
            //TODO - do something with the NodeList
            c_pData = c_thisXmlParser.NodeList;

            OnQueryFinished(c_pData, null, null, c_pData);
        }
        catch
        {
            OnQueryFinished(null, null, null, null);
        }
    }

XmlNode 定义为:

 public class XmlNode
{
    public string Tag { get; set; }
    public string Type { get; set; }
    public string InnerText { get; set; }
    public int FileNumber { get; set; }
    public int NodeDepth { get; set; }
    public int IndexNumber { get; set; }
}

这是列表中的第一个元素:

结果列表在窗口中显示如下:

上面的列表应该包含一个 Tag 元素的列表,我无法正确理解为什么 Path 参数没有收集 List 的正确元素,而是提供了第一个 list-elements tag-name 的列表.

【问题讨论】:

    标签: c# wpf listbox dataprovider


    【解决方案1】:

    您通常绑定到ItemsSource 的是一个包含一些元素集合的属性。您已绑定属性Tag,它是一个字符串,而字符串恰好是字符的集合。这就是为什么每个列表项都包含 foodlist 的单个字符,并且 WPF 非常乐意将此绑定解释为 FirstOrDefault。您的绑定有什么问题是 Path 应该是空的。然后在你的标签中它是空的,它应该是Tag。

    <ListBox Grid.Row="1" ItemsSource="{Binding, Source={ StaticResource txtProvider}}"
                 DockPanel.Dock="Bottom">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Label Content="{Binding Path=Tag}" FontFamily="Arial" FontWeight="Normal" Margin="5,0,0,0"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    

    【讨论】:

    • 我只是喜欢它,当不知道的低效率由简单本身解决时。唯一的问题是你会觉得自己很愚蠢 :) 非常感谢。
    • 让我感到困惑的是,原始代码是 Binding with with Path=.,,它给了我一个 XmlNode 元素的列表。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 2012-04-28
    • 2014-01-31
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    相关资源
    最近更新 更多