我正在尝试使用 XamlReader 在运行时解析 XAML 文件。不幸的是,当 XamlReader 尝试读取相对属性(如relativepanel.below)时,我收到 XamlParseException。
这是加载 xaml 文件的代码:
using System;
using System.IO;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Markup;
namespace TestProject.UWP.Views
{
public sealed partial class LoginPage : Page
{
public LoginPage()
{
this.InitializeComponent();
Loaded += OnLoaded;
}
private async void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
{
var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
folder = await folder.GetFolderAsync("TestData");
var file = await folder.GetFileAsync("LoginControl.xaml");
var xaml = await FileIO.ReadTextAsync(file);
var content = (UserControl)XamlReader.Load(xaml);
this.Content = content;
}
}
}
这是我尝试从本地内容读取的 xaml 文件
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TestProject.UWP.Views"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="800"
d:DesignWidth="600">
<RelativePanel Background="LightGray">
<Border x:Name="logoBorder" BorderBrush="White" BorderThickness="0,0,0,1" Margin="30,30,30,10" Width="200" Height="60" Padding="0,0,0,5" RelativePanel.AlignLeftWithPanel="True" RelativePanel.AlignRightWithPanel="True" RelativePanel.AlignTopWithPanel="True" >
<Image Stretch="Uniform" Source="ms-appx:///Assets/Images/logo.png" Width="200" />
</Border>
<Image x:Name="userIcon" Source="ms-appx:///Assets/Images/usericon.png" Margin="30,10" RelativePanel.AlignHorizontalCenterWithPanel="True" RelativePanel.AlignRightWith="logoBorder" Width="100" Height="100"/>
</RelativePanel>
</UserControl>
当我尝试解析 xaml 时,出现以下异常: “WinRT 信息:RelativePanel 错误:值必须属于 UIElement 类型。”
一旦我从第二个图像中删除属性RelativePanel.AlignRightWith =“logoBorder”,一切都会正常工作。
有人有办法解决这个问题吗?
编辑: 在你问之前。稍后应该从服务器加载 xaml,这就是为什么我不只是在代码中实例化用户控件的实例。
干杯
科内利斯
最佳答案
替换元素名称
RelativePanel.AlignRightWith="logoBorder"
通过 ElementName 绑定(bind):
RelativePanel.AlignRightWith="{Binding ElementName=logoBorder}"
关于xaml - WinRT/UWP : Loading RelativePanel with XamlReader causes XamlParseException with RelativePanels Attached Properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31986328/