Windows应用商店应用程序绑定列表中的ListView和来自" Self"

时间:2014-07-22 09:06:16

标签: c# windows xaml binding store


我在Window Store应用程序中将数据绑定到ListView时遇到问题。我想要的是,将listview绑定到一个集合并在listview datatemplate中显示项目(可行)。我有问题的地方是,当我想在这个模板中显示一个变量,它没有在集合中定义,但在类中是公共的。
让我展示一些代码,以解决我的问题 我在XAML中定义了布局:

<Page.Resources>
    <DataTemplate x:Key="template">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding}"/>
            <TextBlock Text="{Binding Test}" Margin="20 0" />
        </StackPanel>
    </DataTemplate>
</Page.Resources>

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <ListView ItemTemplate="{StaticResource template}" ItemsSource="{Binding Items}" x:Name="listView" Margin="40">
    </ListView>
</Grid>

背后的代码是:

public List<string> Items { get; set; }
public string Test { get; set; }
public MainPage()
{
    this.InitializeComponent();
    Items = new List<string>()
    {
        "test 1", "test 2" , "test 3"
    };
    Test = "TEST!";

    listView.DataContext = this;
}

我需要设置什么,TextBlock会正确绑定Test变量吗?

1 个答案:

答案 0 :(得分:1)

试试这个..

<Page.Resources>
    <DataTemplate x:Key="template">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding}"/>
            <TextBlock Text="{Binding ElementName=listView, Path=DataContext.Test}" Margin="20 0" />
        </StackPanel>
    </DataTemplate>
</Page.Resources>

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <ListView ItemTemplate="{StaticResource template}" ItemsSource="{Binding Items}" x:Name="listView" Margin="40">
    </ListView>
</Grid>