代码和 xaml 中的 ListBox.ItemsSource 绑定
编写了简单的代码,例如
public ObservableCollection<string> Names …
public Window1()
{
PutInDataIntoNames();
InitializeComponent();
this.listBox1.ItemsSource = Names;
}
我在 xaml 中
<Grid>
<ListBox Margin="10,11,10,16"
Name="listBox1"
Background="Black"
Foreground="Orange"
/>
</Grid>
和然后我想在 xaml 中设置 ItemsSource 属性。为了做到这一点,我写了以下内容:
ItemsSource="{Binding Path=Names}"
不幸的是,它不起作用。您能解释一下为什么以及如何正确地做到这一点吗?
I wrote simple code like
public ObservableCollection<string> Names …
public Window1()
{
PutInDataIntoNames();
InitializeComponent();
this.listBox1.ItemsSource = Names;
}
and in xaml
<Grid>
<ListBox Margin="10,11,10,16"
Name="listBox1"
Background="Black"
Foreground="Orange"
/>
</Grid>
Then I wanted to set ItemsSource property in xaml. In order to do that I wrote the following:
ItemsSource="{Binding Path=Names}"
Unfortunately, it doesn’t work. Could you explain why and how to do that right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您仅指定绑定路径,绑定引擎将尝试从当前
DataContext
开始导航路径,因此ItemsSource="{Binding Path=Names}"
不会像这样工作这一点,有很多不同的事情需要记住,特别是在做更复杂的事情时。每个刚接触 DataBinding 的人都应该阅读的最重要的一篇文章是 MSDN 上的数据绑定概述
要回到您的绑定,如果您想完全在 XAML 中完成它,您也可以这样做,您只需以某种方式使 Window 成为您的源,可以通过直接或相对引用它,也可以通过将其设置为 DataContext 。
1 - 直接引用:
2 - 相对引用
3 - 设置 DataContext
If you only specify the binding path the binding engine will try to navigate the path starting from the current
DataContext
soItemsSource="{Binding Path=Names}"
does not work like this, there are a lot of different things to keep in mind especially when doing more complex things.The single most important article that everyone who is new to DataBinding should read is the Data Binding Overview on MSDN
To get back to your binding, if you want to do it completely in XAML you can do that as well, you just need to make the Window your source somehow, either by referencing it directly or relatively or by setting it up as the DataContext.
1 - Direct Reference:
2 - Relative Reference
3 - Setting up the DataContext
在代码隐藏
和 XAML 中
执行此操作理想情况下,您应该遵循 MVVM 设计将数据与代码隐藏隔离。
Do this in code behind
and in XAML
Ideally you should follow MVVM design to isolate data from code behind.
您的
Names
似乎可能是一个字段。您只能绑定到公共属性It seems that your
Names
might be a field. You can ONLY bind to public properties