NickThomsan
NickThomsan

Reputation: 51

WinRT Binding data of ViewMode inside a DataTemplate

I wanted to bind data inside a DataTemplate that is stored in ViewModel. I've tried several ways but did not succeed and the solutions for WPF doesn't seems to work on WinRT like AncestorType Property of RelativeSource.

<Page.DataContext>
    <local:ViewModel x:Name="ViewModel" />
</Page.DataContext>

<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <ListView ItemsSource="{x:Bind ViewModel.names}">
        <ListView.ItemTemplate>
            <DataTemplate x:DataType="local:mydatatype">
                <StackPanel>
                    <TextBlock Text="{Binding Name}"/>
                    <!--Here I want a TextBlock to show the number-->
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</StackPanel>

Here is the ViewModel

public class ViewModel
{
    public int Number = 42;
    public List<mydatatype> names = new List<mydatatype>();
    public ViewModel()
    {
        names.Add(new mydatatype("name1"));
        names.Add(new mydatatype("name2"));
    }
}

public class mydatatype
{
    public string Name { get; set; }
    public mydatatype(string name)
    {
        this.Name = name;
    }
}

Upvotes: 3

Views: 210

Answers (1)

NotAGenie
NotAGenie

Reputation: 475

You can access the DataTemplate of other objects by giving them a name and then referencing this. Using this technique you should be able to access its DataContext to bind to the viewmodel directly, even from within a DataTemplate

<Page x:Name="PageRoot">
<Page.DataContext>
    <local:ViewModel x:Name="ViewModel" />
</Page.DataContext>

<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" x:Name="MainPanel">
    <ListView ItemsSource="{x:Bind ViewModel.names}">
        <ListView.ItemTemplate>
            <DataTemplate x:DataType="local:mydatatype">
                <StackPanel>
                    <TextBlock Text="{Binding Name}"/>
                    <TextBlock Text="{Binding DataContext.Name, ElementName=PageRoot}"/>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</StackPanel>
</Page>

Upvotes: 1

Related Questions