【发布时间】:2013-01-10 13:51:09
【问题描述】:
我有一个数据类:
public class routedata : INotifyPropertyChanged
{
private List<double> distances;
public List<double> Distances
{
get { return this.distances; }
set
{
if (this.distances != value)
{
this.distances = value;
this.onPropertyChanged("Distances");
}
}
}
private List<string> instructions;
public List<string> Instructions
{
get { return this.instructions; }
set
{
if (this.instructions != value)
{
this.instructions = value;
this.onPropertyChanged("Instructions");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void onPropertyChanged(string property)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
我正在尝试将它绑定到这样的列表视图:
<GridView Name="routeView" HorizontalAlignment="Left" Height="310" Margin="1025,318,0,0" Grid.Row="1"
VerticalAlignment="Top" Width="340" >
<ListView Name="routeList" Height="300" Width="330" ItemsSource="{Binding routeData}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Instructions}"
TextWrapping="Wrap" Width="200"/>
<TextBlock Text="{Binding Distances}"
Margin="10,0,0,0" />
<TextBlock Text="km"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</GridView>
我的 c# 代码后面有:routeList.datacontext = this;
但它仍然没有绑定,列表视图中只填充了一个空行。我检查了数据,它都存在。任何帮助将不胜感激,谢谢。
【问题讨论】:
-
你有一个 routedata 实例?还是路由数据元素列表?您的 GridView ItemsSource 暗示后者。 ItemSource 应设置为一个集合,然后在您的模板中将 UI 元素分配给该集合中类的各个成员。你似乎有一个倒置的场景。
-
我明白了。我有一个路由数据实例。我应该将列表视图放在网格内吗?我以前试过这个,它仍然没有用。感谢您的回复。
-
您的路线元素是一个对象,其中有两个不同的集合,但您正试图将两个集合逐项拉入一个网格中。如果说明和距离列表的大小不同会怎样?请参阅下面的@FilipSkakun 答案;您的数据模型需要进行一些修改,然后绑定将自然流动。
-
我可以保证指令和距离总是一样的。我之前使用了另一种方法,但没有正确注册 onselectionchanged 处理程序。但我正在尝试实现正确的方法 atm。
标签: c# xaml listview data-binding windows-8