C# WPF:最简单的项控件将不显示任何项
我无法让最简单的C# WPF:最简单的项控件将不显示任何项,c#,wpf,datatemplate,itemscontrol,itemtemplate,C#,Wpf,Datatemplate,Itemscontrol,Itemtemplate,我无法让最简单的ItemControl工作。我只想用一堆SomeItem填充我的ItemsControl 这就是背后的代码: using System.Collections.ObjectModel; using System.Windows; namespace Hax { public partial class MainWindow : Window { public class SomeItem { publi
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"));
}
}
}
使用System.Collections.ObjectModel;
使用System.Windows;
名称空间Hax
{
公共部分类主窗口:窗口
{
公共类项目
{
公共字符串文本{get;set;}
公共项目(字符串文本)
{
文本=文本;
}
}
公开收集参与者
{get{return m_Participants;}set{m_Participants=value;}}
私人可观察收集m_参与者
=新的ObservableCollection();
公共主窗口()
{
初始化组件();
添加(新的SomeItem(“Hej!”);
添加(新的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>
我做错了什么?ItemsSource引用了一个名为MyParticipants的属性,而代码看起来是参与者
检查调试输出视图,您应该会看到错误消息。确保您的datacontext在xaml中的某个位置设置为RelativeSource Self。如果您可以发布更多的xaml,可能会有所帮助
<ItemsControl... DataContext="{Binding RelativeSource={RelativeSource Self}}" >
很抱歉,这只是复制粘贴代码、替换某些变量名时的一个错误。我会更新问题的。酷。我仍然建议查看Debug Output视图,因为您应该会在那里看到可能导致答案的错误消息。我将DataContext=“{Binding RelativeSource={RelativeSource Self}}”添加到解决问题的窗口元素。这是标准方式吗?是的,在窗口级别添加它可能是最标准的方式。从技术上讲,您可以将其添加到树中的任何位置,只要它位于要绑定的元素之上。您的回答是正确的,但您的注释包含错误。如果在树中除窗口级别之外的任何位置添加DataContext
绑定,relativesourceself
对显示的代码无效:必须改用relativesourcefindancestor
。@Ray Burns,你是对的,感谢您的更新——如果您要将DataContext绑定到RelativeSource Self,并希望它从嵌套元素绑定到窗口的CodeBehind,则需要使用RelativeSource FindAncestor,正如Ray所说。