【发布时间】:2016-07-12 22:57:52
【问题描述】:
我有一个包含可观察字符串集合的对象,如何绑定数据网格以显示这些字符串?
举个例子:
public class Container
{
public ObservableCollection<string> strs; //This won't work, see edit!
.
.
.
}
XAML:
<DataGrid ItemsSource="{Binding Container}" AutoGenerateColumns="False" >
<DataGrid.Columns>
<DataGridTextColumn Header="Strings" Binding="{Binding}" />
</DataGrid.Columns>
</Datagrid>
为搜索者编辑:上述方法存在一些问题,首先您可以通过简单地引用这些属性来绑定到项目的属性。在这种情况下:
ItemsSource="{Binding Container.strs}"
其次,字符串的内容不是字符串的属性,所以
Binding="{Binding}"
直接绑定到字符串,而不是试图找到它的属性(例如长度)
最后你不能绑定到字段,只能绑定属性,有什么区别?
public ObservableCollection<string> strs; //This is a field
public ObservableCollection<string> strs {get; set;} //This is property
奖励:如果您只是实例化 strs 一次,那么 ObservableCollection 将在更改到/在其中发生时通知其绑定的任何内容,但如果您更改指针,则不会,修复这你可以使用依赖属性!
在visual studio中最好使用内置的sn-p,因为有很多东西要填写type:'propdp'并点击两次tab,在这种情况下我们会有:
public ObservableCollection<string> strs
{
get { return (ObservableCollection<string>)GetValue(strsProperty); }
set { SetValue(strsProperty, value); }
}
// Using a DependencyProperty as the backing store for strs. This enables animation, styling, binding, etc...
public static readonly DependencyProperty strsProperty =
DependencyProperty.Register("strs", typeof(ObservableCollection<string>), typeof(Container), new PropertyMetadata(""));
【问题讨论】: