Kir*_*kov 9 wpf listbox itemssource
我写了简单的代码
public ObservableCollection<string> Names …
public Window1()
{
PutInDataIntoNames();
InitializeComponent();
this.listBox1.ItemsSource = Names;
}
Run Code Online (Sandbox Code Playgroud)
并在xaml
<Grid>
<ListBox Margin="10,11,10,16"
Name="listBox1"
Background="Black"
Foreground="Orange"
/>
</Grid>
Run Code Online (Sandbox Code Playgroud)
然后我想在xaml中设置ItemsSource属性.为了做到这一点,我写了以下内容:
ItemsSource="{Binding Path=Names}"
Run Code Online (Sandbox Code Playgroud)
不幸的是,它不起作用.你能解释为什么以及如何做到这一点吗?
H.B*_*.B. 10
如果你只指定绑定路径绑定引擎将尝试从当前开始导航路径,DataContext所以ItemsSource="{Binding Path=Names}"不能像这样工作,要记住很多不同的事情,特别是在做更复杂的事情时.
每个对DataBinding不熟悉的人都应阅读的最重要的一篇文章是MSDN上的数据绑定概述
要回到绑定,如果你想在XAML中完全执行它,你也可以这样做,你只需要以某种方式使Window成为你的源,可以通过直接或相对引用它或者将它设置为DataContext.
1 - 直接参考:
<Window Name="Window"
...>
<Grid>
<ListBox ...
ItemsSource="{Binding ElementName=Window, Path=Names}"
.../>
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)
2 - 相对参考
<Grid>
<ListBox ...
ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=Names}"
.../>
</Grid>
Run Code Online (Sandbox Code Playgroud)
3 - 设置DataContext
<Window ...
DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}">
<Grid>
<ListBox ...
ItemsSource="{Binding Path=Names}"
.../>
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)
在后面的代码中执行此操作
public Window1()
{
PutInDataIntoNames();
InitializeComponent();
DataContext = this;
}
Run Code Online (Sandbox Code Playgroud)
在XAML中
<Grid>
<ListBox ItemsSource="{Binding Names}"
Margin="10,11,10,16"
Name="listBox1"
Background="Black"
Foreground="Orange"
/>
</Grid>
Run Code Online (Sandbox Code Playgroud)
理想情况下,您应该遵循MVVM设计,以将数据与背后的代码隔离开。
| 归档时间: |
|
| 查看次数: |
22856 次 |
| 最近记录: |