【问题标题】:WPF: Simplest ItemsControl will not display any itemsWPF:最简单的 ItemsControl 不会显示任何项目
【发布时间】:2010-01-25 13:20:10
【问题描述】:

我无法让ItemControl 工作的最简单的想法。我只想用一堆SomeItem 填充我的ItemsControl

这是代码隐藏:

using System.Collections.ObjectModel;
using System.Windows;

namespace Hax
{

    public partial class MainWindow : Window
    {

        public class SomeItem
        {
            public string Text { get; set; }
            public SomeItem(string text)
            {
                Text = text;
            }
        }

        public ObservableCollection<SomeItem> Participants
            { get { return m_Participants; } set { m_Participants = value; } }
        private ObservableCollection<SomeItem> m_Participants
            = new ObservableCollection<SomeItem>();

        public MainWindow()
        {
            InitializeComponent();
            Participants.Add(new SomeItem("Hej!"));
            Participants.Add(new SomeItem("Tjenare"));
        }
    }
}

这是 XAML:

<ItemsControl Name="itemsParticipants"
    ItemsSource="{Binding Path=Participants}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Border BorderBrush="Red" BorderThickness="2">
                <TextBlock Text="{Binding Text}" />
            </Border>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

我做错了什么?

【问题讨论】:

    标签: c# wpf datatemplate itemscontrol itemtemplate


    【解决方案1】:

    确保您的 datacontext 在您的 xaml 中某处设置为 RelativeSource Self。如果您可以发布更多您的 xaml,它可能会有所帮助。

    <ItemsControl... DataContext="{Binding RelativeSource={RelativeSource Self}}" >
    

    【讨论】:

    • 我将DataContext="{Binding RelativeSource={RelativeSource Self}}" 添加到解决了问题的Window 元素中。这是标准方式吗?
    • 是的,在窗口级别添加它可能是最标准的。从技术上讲,您可以将它添加到树中的任何位置,只要它位于您要绑定的元素之上。
    • 您的答案是正确的,但您的评论包含错误。如果您在树中除窗口级别之外的任何位置添加DataContext 绑定,RelativeSource Self 将不适用于显示的代码:您必须改用RelativeSource FindAncestor
    • @Ray Burns,您是正确的,感谢您的更新——如果您将 DataContext 绑定到 RelativeSource Self 并希望它从嵌套元素绑定到 Window 的 CodeBehind,您需要正如 Ray 所说,使用 RelativeSource FindAncestor。
    【解决方案2】:

    ItemsSource 引用了一个名为 MyParticipants 的属性,而它看起来是 Participants 的代码。

    检查调试输出视图,您应该会看到错误消息。

    【讨论】:

    • 对不起,这只是复制粘贴代码时的错误,替换了一些变量名。我会更新问题。
    • 酷。我仍然建议查看 Debug Output 视图,因为您应该在那里看到可能导致答案的错误消息。
    猜你喜欢
    • 2019-06-23
    • 1970-01-01
    • 2015-08-09
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    • 1970-01-01
    相关资源
    最近更新 更多