简体   繁体   中英

UWP DataContext from DataTempalte to UserControl in DataTemplate

I want to share a ListViewItem from DataTemplate to a UserControl in DataTemplate using DataContext, i just spend two hours on this task, looked many sites, but dont find a requested answer, because everytime i want to get DataContext, it is null.

Short code, what i want to do:

In Page.xaml

<ListView Name="MainWindowLinesInfoListView1" IsItemClickEnabled="True" ItemClick="MainWindowLinesInfoListView1_ItemClick" Grid.Row="1" ItemsSource="{x:Bind pk1}" SelectionMode="Single">
       <ListView.ItemTemplate>
            <DataTemplate x:DataType="data:Przystanki">
                <local:MainWindowLinesInfoFirst DataContext="{x:Bind self}" />
            </DataTemplate>
        </ListView.ItemTemplate>
</ListView>

in UserControl called: MainWindowLinesInfoFirst

<Grid Margin="2" HorizontalAlignment="Center">
    <TextBlock x:Name="MainWindowLinesInfoListView1TextBlock" Foreground="Navy" HorizontalAlignment="Center" TextWrapping="Wrap" />
</Grid>

and in .cs of this UserControl:

public MainWindowLinesInfoFirst()
{
    this.InitializeComponent();
    var a = this.DataContext as Przystanki;
}

and here is a simple class:

public class Przystanki
{
    public Przystanki self { get { return this; } }
    public string name { get; set; }
}

The problem is, that always when a this UserControl is called, a DataContext is not a "Przystanki" bot null.

Question is: How to send a DataContext to this UserControl?

What UWP does:

  1. Creates MainWindowLinesInfoFirst control.
  2. Sets its DataContext property to your required value.

Obviously, you can't read DataContext property in the constructor, because the control isn't created yet and there's no way for UWP to set a property before creating an instance.

What you want is to subscribe to the DataContextChanged event in the constructor. When UWP sets it, you'll be notified.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM