简体   繁体   English

从DataTempalte到DataTemplate中的UserControl的UWP DataContext

[英]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. 我想使用DataContext从DataTemplate共享一个ListViewItem到DataTemplate中的UserControl,我只花了两个小时完成这个任务,查看了很多站点,但没有找到请求的答案,因为每次我想获得DataContext,它都是null。

Short code, what i want to do: 简短的代码,我想做的:

In Page.xaml 在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 在UserControl中调用:MainWindowLinesInfoFirst

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

and in .cs of this UserControl: 并在此UserControl的.cs中:

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. 问题是,总是在调用此UserControl时,DataContext不是“Przystanki”bot null。

Question is: How to send a DataContext to this UserControl? 问题是:如何将DataContext发送到此UserControl?

What UWP does: UWP的作用:

  1. Creates MainWindowLinesInfoFirst control. 创建MainWindowLinesInfoFirst控件。
  2. Sets its DataContext property to your required value. 将其DataContext属性设置为所需的值。

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. 显然,您无法在构造函数中读取DataContext属性,因为尚未创建控件,并且在创建实例之前UWP无法设置属性。

What you want is to subscribe to the DataContextChanged event in the constructor. 你想要的是订阅构造函数中的DataContextChanged事件。 When UWP sets it, you'll be notified. 当UWP设置它时,您将收到通知。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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