0
votes


I have a problem with binding data to ListView in Window Store application. What I want is, to bind listview a collection and show items in listview datatemplate (that works). Where I have problem is, when I want show in this template a variable, which is not defined in collection, but is public in class.
Let me show some code, to clear my problem.
I have defined layout in 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>

And code behind is:

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;
}

What I need to set, that will TextBlock properly bind Test variable?

1
Bind to the Grid's DataContext.Test or ListView's DataContext.Testbit

1 Answers

1
votes

Try this..

<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>