[英]WPF project integrating a UWP Xaml Island GridView
我正在嘗試在我的 WPF 項目中使用 UWP 中的 GridView 控件。 我的目標是擁有 3 行的水平滾動容器,因此 WPF ListView 是不夠的; 觸摸設備的性能也很差。 另一件事是我對 UWP 的 GridView 有經驗,並且控制超出了 WPF 必須提供的任何東西。
所以我從使用 WindowsXamlHost 的 Xaml 島開始:
xmlns:xamlhost="clr-namespace:Microsoft.Toolkit.Wpf.UI.XamlHost;assembly=Microsoft.Toolkit.Wpf.UI.XamlHost"
<xamlhost:WindowsXamlHost InitialTypeName="Windows.UI.Xaml.Controls.GridView"
x:Name="MainGrid"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
ChildChanged="MainGrid_ChildChanged">
</xamlhost:WindowsXamlHost>
是否可以在主機的 xaml 聲明中添加 ItemsSource? 如果我添加它,我會得到 ItemsSource 不是 XamlHost 的成員。 這意味着它不被識別為 GridView。
因為我無法在 xaml 中添加 ItemsSource,所以我在代碼中做到了:
private void MainGrid_ChildChanged(object sender, EventArgs e) { WindowsXamlHost windowsXamlHost = (WindowsXamlHost)sender; Windows.UI.Xaml.Controls.GridView gridView = (Windows.UI.Xaml.Controls.GridView)windowsXamlHost.Child; if (gridView;= null) { MainGridView = gridView. MainGridView;ItemsSource = Items; } }
這解決了 ItemsSource 問題。
我最后一次嘗試是在 assets 文件夾中有一個 xaml 文件,該文件將保存 DataTemplate,讀取它並創建一個 UWP DataTemplate 並將其傳遞給 GridView。
private void testDataTemplate()
{
using (Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(path))
{
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
object root = Windows.UI.Xaml.Markup.XamlReader.Load(text) as Windows.UI.Xaml.DataTemplate;
Windows.UI.Xaml.DataTemplate temp = root as Windows.UI.Xaml.DataTemplate;
// pass the Data Template to the UWP GridView - temp is valid
MainGridView.ItemTemplate = temp;
}
}
此時,應用程序已准備好構建和運行。 結果是應用程序啟動,按原樣出現在屏幕上,然后凍結,我得到經典應用程序沒有響應。
有沒有人在 WPF 內使用過 UWP GridView? 在這種情況下是否有更智能的解決方案來使用 DataTemplates?
更新:似乎問題來自 DataTemplate。 如果我將一個簡單的文本顯示為 DataTempalte,它將顯示出來。 但是我在那個 DataTemplate 中有一些綁定要做:
<DataTemplate xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
x:DataType="MovieObject">
<Grid Width="254" Height="160" Margin="0" Padding="0">
當我引用 MovieObject 並嘗試綁定它的屬性時,應用程序會中斷。 那么如何在 template.xaml 文件中使用 object 進行綁定。 現在應用程序在點擊 x:DataType="MovieObject" 時會中斷。
是否可以在主機的 xaml 聲明中添加 ItemsSource?
不,您應該像當前所做的那樣以編程方式設置由WindowsXamlHost
創建的類型的實例的ItemsSource
。 主機本身沒有ItemsSource
屬性。 即使您從Child
屬性中獲取實例,您仍然必須強制轉換它。
當涉及到模板定義時,您可以刪除x:DataType
屬性並將任何已編譯的綁定 ( x:Bind
) 替換為常規動態{Binding}
表達式:
<DataTemplate xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Grid Width="254" Height="160" Margin="0" Padding="0">
<TextBlock Text="{Binding SomePropertyOfMovieObject}" />
</Grid>
</DataTemplate>
XamlReader.Load
不支持x:DataType
屬性,該屬性僅用於能夠使用在模板中的編譯時驗證的已編譯綁定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.