【问题标题】:Bind ListBoxItems using Code使用代码绑定 ListBoxItems
【发布时间】:2010-12-15 09:48:08
【问题描述】:

我尝试使用代码绑定 XAML ListBoxItem,但似乎不起作用

在我的 XAML 中:

<Window.Resources>
    <local:FooList x:Key="FooListItem" />
</Window.Resources>

在我的代码中:

public class FooList
{
    add some items; // I tried variation of that but didn't get it to work
}

有什么建议吗?

【问题讨论】:

    标签: c# wpf data-binding


    【解决方案1】:

    您不会从代码中创建ListBoxItem

    您只需提供一个带有 CLR 类对象集合的ListBox,提供一个ItemTemplate,它会在ListBoxItem 内隐式包装一个ItemTemplate

    例子:

    public class FooList
    {
        public ObservableCollection<String> Items { get; set; }
    
        public FooList()
        {
            Items = new ObservableCollection<String>();
        }
    }
    

    XAML:

    <ListBox x:Name="ListBox1" ItemsSource="{Binding Path=Items, Source={StaticResource FooListItem}}" />
    

    【讨论】:

    • 我可以在 XAML 中做到这一点。但我不能在代码中做到这一点?您如何在代码中提供 ItemTemplate?
    • 感谢您提供更多详细信息。但我需要在没有 observableCollection 的情况下这样做。我正在关注本教程:msdn.microsoft.com/en-us/library/… 他们能够绑定 ItemsSource 但没有提供任何解释...
    • 那是因为该示例中的Tasks 类型本身就是Collection
    • 我想我的问题没有说清楚,请看这个问题stackoverflow.com/questions/4451171
    【解决方案2】:

    【讨论】:

    猜你喜欢
    • 2011-07-26
    • 1970-01-01
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多