C# 具有编译绑定的hubbsection

C# 具有编译绑定的hubbsection,c#,xaml,windows-10,uwp,compiled-bindings,C#,Xaml,Windows 10,Uwp,Compiled Bindings,我试图掌握新的编译绑定,但一开始我就被这个简单的问题所阻止 我有Hub控件和一个HubSection。本节的内容是一个ItemsControl,需要绑定到视图模型的可观察集合。我不能让这个装订像我期望的那样工作 <Pivot x:Name="rootPivot" Style="{StaticResource TabsStylePivotStyle}"> <PivotItem> <Hub> <HubSecti

我试图掌握新的编译绑定,但一开始我就被这个简单的问题所阻止

我有
Hub
控件和一个
HubSection
。本节的内容是一个
ItemsControl
,需要绑定到视图模型的可观察集合。我不能让这个装订像我期望的那样工作

<Pivot x:Name="rootPivot" Style="{StaticResource TabsStylePivotStyle}">
    <PivotItem>
        <Hub>
            <HubSection Header="News">
                <DataTemplate x:DataType="local:HomePage">
                    <ItemsControl ItemsSource="{x:Bind ViewModel.NewsItems, Mode=OneWay}" />
HomePageViewModel.cs

/// <summary>
/// Home view model.
/// </summary>
public sealed class HomeViewModel : IHomeViewModel
{
    /// <summary>
    /// Occurs on page loaded.
    /// </summary>
    public async Task LoadedAsync()
    {
        // Retrieve news items
        var news = await new NewsService().GetNewsAsync();
        foreach (var newsItem in news)
            this.NewsItems.Add(newsItem);
    }

    /// <summary>
    /// Gets the news items.
    /// </summary>
    /// <value>
    /// The news items.
    /// </value>
    public ObservableCollection<IFeedItem> NewsItems { get; } = new ObservableCollection<IFeedItem>();
}
//
///主视图模型。
/// 
公共密封类HomeViewModel:IHomeViewModel
{
/// 
///在加载的页面上发生。
/// 
公共异步任务LoadedAsync()
{
//检索新闻项目
var news=等待新的新闻服务().GetNewsAsync();
foreach(新闻中的var newsItem)
this.NewsItems.Add(newsItem);
}
/// 
///获取新闻项。
/// 
/// 
///新闻项目。
/// 
公共ObservableCollection新闻项{get;}=new ObservableCollection();
}

这确实是一个有趣的问题。我想问题在于,与典型的
DataTemplate
不同,如下所示(请参见其父级
ListView
绑定到一些已知的数据
模型。项

或者简单地加上

this.InitializeComponent();
this.DataContext = this;

无论哪种方法都可以解决您的问题。

您可能希望在代码后面显示代码。这有帮助吗@JustinXL@JustinXL我不。只有这个方法在加载时才被调用,所以我不在乎它是否在视图模型加载完成之前继续。抛开其他问题不谈,您正在执行一个错误的异步任务。有大量的样品,所以这样做正确。e、 g.
this.Loaded+=async(发送方,参数)=>等待this.ViewModel.LoadedAsync()会更好吗?当您只调用一个方法时,效果是一样的,您不需要(a)等待它完成。我没有找到从
void-Loaded
方法调用异步方法的任何其他方法。这肯定不是问题所在@贾斯汀:我仍然建议你重新考虑如何调用该服务,但这与问题无关。我之前提供的链接应该给你一些提示。这只是一个简单的例子。我省略了一堆代码。我在real app中使用DI、facades等@Justin XLThis解决了我的问题,但另一个注意事项是:如果没有
x:DataType=“{TheType}”
,我就不能使用
,因此我将
更改为
,现在可以根据HUB部分的要求在列表视图周围放置一个空白的
<ListView ItemsSource="{x:Bind Model.Items}">
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="model:Item">
            <Grid>
                <TextBlock Text="{x:Bind Name}" />
            </Grid>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
<Hub DataContext="{x:Bind}">
this.InitializeComponent();
this.DataContext = this;