windows store app Listview绑定

时间:2013-01-26 20:52:32

标签: c# xaml listview data-binding windows-8

我有一个包含数据的课程:

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;

但它仍然没有绑定,列表视图中只填充了一个空行。我检查了数据,它都存在。任何帮助将不胜感激,谢谢。

2 个答案:

答案 0 :(得分:1)

ListView将单个集合作为ItemsSource,因此如果要为每个项目显示多个TextBlock,则需要具有多个文本属性的对象集合以绑定到DataTemplate。在您的情况下,routeData不是集合。相反,您需要定义项目视图模型,例如

public class RoutePoint
{
    public double Distance { get; set; }
    public string Instruction { get; set; }
}

然后你将ListView.ItemSource绑定到List,并在你的DataTemplate中绑定它:

<TextBlock Text="{Binding Distance}"/>
<TextBlock Text="{Binding Instruction}"/>

如果您的集合在第一次将其绑定到ListView后永远不会更改,则不需要使用ObservableCollection(SelectedItem不构成更改)。

答案 1 :(得分:0)

如果您的观点被称为routeView,那么您的DataContext不应该设置为routedata的新实例吗?另外,我建议您使用ObservableCollection<T>作为可绑定集合,而不是List<T>