【问题标题】:Data not binding to ListBox WPF数据未绑定到 ListBox WPF
【发布时间】:2017-11-19 10:56:35
【问题描述】:

XAML

<Page x:Class="ManufacturingWPF.ShowHardware"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
  xmlns:local="clr-namespace:ManufacturingWPF"
  mc:Ignorable="d" 
  d:DesignHeight="300" d:DesignWidth="300"
  Title="ShowHardware">



<Grid Background="AliceBlue">
    <ListBox x:Name="HardwareList" ItemsSource="{Binding Hardware}"  HorizontalAlignment="Left" Height="122" Margin="76,36,0,0" VerticalAlignment="Top" Width="149">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding ID}"/>
                    <TextBlock Text="{Binding Date}"/>
                    <TextBlock Text="{Binding Nodes}"/>
                    <TextBlock Text="{Binding Repeaters}"/>
                    <TextBlock Text="{Binding Hubs}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

</Grid>

C# 背后的代码

public partial class ShowHardware : Page
{
    public ShowHardware()
    {
        InitializeComponent();
        DisplayData();

    }

    public void DisplayData()
    {
         //Datamodel MDM used for ADO and table creation
         //Test is a class used to pass the model and as the name suggest 
         test it

        ManufacturingDataModel MDM = new ManufacturingDataModel();
        Test t = new Test(MDM);

        List<Hardware> x = t.GetHardware();

        foreach(Hardware i in x )
        {
            HardwareList.ItemsSource = i.Hubs.ToString();
        }
    }

}

}

我遇到了将数据绑定到列表框的问题,如 XAML 和代码隐藏内容中所示。 我已经尝试过以前的答案,但没有任何运气,我进行了研究,但显然我错过了一些东西,或者可能有些东西我不太明白。 顾名思义,Itemsource 应该绑定到保存我的数据的源。在这种情况下,源将是我的类硬件,它保存节点、日期、集线器等的数据。 在文本块中,我手动绑定这些属性并显示值。 但这行不通。 附:我的数据库表已填充。

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    那是因为 ItemsSource 是一个 IEnumerable 并且您为其分配了硬件本身的列表。所以你的代码应该是这样的:

    ManufacturingDataModel MDM = new ManufacturingDataModel();
    Test t = new Test(MDM);
    
     List<Hardware> x = t.GetHardware();
     HardwareList.ItemsSource = x;
    
    //or
    foreach (Hardware h in x)
      HardwareList.Items.Add(h);
    

    【讨论】:

    • 欢迎回答。有效 。非常感谢:)
    【解决方案2】:

    这段代码好像错了

    foreach(Hardware i in x )
    {
        HardwareList.ItemsSource = i.Hubs.ToString();
    }
    

    那么用于绑定的 ItemsSource 必须是一个集合(ListObservableCollecionIEnumerable&lt;&gt; ...)。

    尝试HardwareList.ItemsSource = x; 并删除foreach loop

    希望对你有帮助。

    【讨论】:

    • 嘿。它确实与上面的答案一致。感谢您的时间和回答!
    • 如果这个或其他答案(或两者)对您有帮助,您可以对其/他们进行投票。快乐编码!
    猜你喜欢
    • 1970-01-01
    • 2014-06-11
    • 2012-06-20
    • 2011-10-06
    • 2017-03-30
    • 2015-09-15
    • 2011-01-02
    • 2011-01-13
    • 1970-01-01
    相关资源
    最近更新 更多