uwp: how to bind data inside DataTemplate outside of x:DataType?

Viewed 833

i have MyPage.xaml and MyPage.xaml.cs files. Into .xaml file i written a data template like this:

        <DataTemplate x:Key="MyDataTemplate" x:DataType="local:MyClass">
            ...
            <TextBlock Text="{x:Bind name}" HorizontalAlignment="Left" TextWrapping="Wrap"/>
            ...
        </DataTemplate>

I can bind name attribute of MyClass correctly. Now i need to bind an attribute of .xaml.cs file but DataTemplate show me only MyClass data. How can i bind data from .xaml.cs page? Outside DataTemplate (but in the same xaml file) i can see any attribute of .xaml.cs file. I need to bind a List of objects to a combobox like this:

<ComboBox ItemsSource="{x:Bind myList}" HorizontalAlignment="Left"></ComboBox>

but myList is an .xaml.cs attribute. I want to view a string name attribute of objects of the list.

Thank you for your help

1 Answers

uwp: how to bind data inside DataTemplate outside of x:DataType?

For your recrement, we suggest you use Binding to replace x:Bind, You could use Binding to access current root DataContext with ElementName.

For example

<Grid x:Name="GridRoot">
    <ListView ItemsSource="{Binding Items}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Name}" />
                    <ComboBox ItemsSource="{Binding ElementName=GridRoot, Path=DataContext.Options}" />
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>

Code Behind

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
        this.DataContext = this;
    }
    public List<string> Options { get; set; } = new List<string>() {"One","Two","Three" };
    public List<Item> Items { get; set; } = new List<Item>() 
    { 
        new Item { Name = "HH" },
        new Item { Name = "ZZ" }, 
        new Item { Name = "MM" }
    };
}
public class Item
{
    public string Name { get; set; }
}
Related