[英]how to use codebehind with a Hub in XAML?
我想在XAML中創建一個包含我的構造網格的Hub
然后,我想使用后面的代碼來設置值
Mikael Koskinen創建了一個很棒的博客文章( http://mikaelkoskinen.net/winrt-xaml-hub-control-getting-started-tutorial-semanticzoom )
下面的示例是他的100%的感謝(感謝博客)-我的問題是-有更好的方法嗎?
<HubSection Header="Trailers">
<DataTemplate>
<ListView x:Name="MovieTrailers">
</ListView>
</DataTemplate>
</HubSection>
即使我們給ListView取了一個名字,我們也不能從后面的代碼中訪問它:
這是因為控件在DataTemplate內部。 克服此限制的一種簡單方法是掛接到ListView的Loaded事件。 這是XAML:
<ListView x:Name="MovieTrailers" Loaded="MovieTrailers_Loaded">
</ListView>
以及后面的代碼:
private void MovieTrailers_Loaded(object sender, RoutedEventArgs e)
{
var listView = (ListView)sender;
listView.ItemsSource = trailers;
}
我遇到了同樣的問題,並最終按照XAML Hub控件示例進行了解決。 它使用CollectionViewSource,我認為這比綁定Loaded事件更好。
首先,定義CollectionViewSource。
<Page.Resources>
<CollectionViewSource x:Name="YourCVS" />
</Page.Resources>
在集線器的ListView上,將其綁定到ItemsSource:
<Hub>
<HubSection Header="ListView">
<DataTemplate>
<ListView ItemsSource="{Binding Source={StaticResource YourCVS}}">
<!-- Your code to actually show things -->
</ListView>
</DataTemplate>
</HubSection>
</Hub>
在后面的代碼中添加數據:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// code to populate the data...
YourCVS.Source = yourListWithData;
}
我在我的項目中遵循了以下說明,但是最終完成了這樣的綁定:
// View constructor
public HubView()
{
this.InitializeComponent();
this.WhenActivated(d =>
{
// ViewModel is a property of this view
d(this.OneWayBind(ViewModel, x => x.MyListWithData, x => x.YourCVS.Source));
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.