WinRT / UWP:使用XamlReader加载RelativePanel会导致XamlParseException和RelativePanels附加属性

时间:2015-08-13 10:58:51

标签: xaml winrt-xaml attached-properties xamlreader uwp

我试图在运行时使用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时,我得到以下异常: &#34; WinRT信息:RelativePanel错误:值必须是UIElement类型。&#34;

我删除属性RelativePanel.AlignRightWith =&#34; logoBorder&#34;从第二张图片来看,每件事都很好。

有人有想法解决这个问题吗?

编辑: 在你问之前。之后应该从服务器加载xaml,这就是为什么我不在代码中实例化用户控件的实例。

干杯

Kornelis

1 个答案:

答案 0 :(得分:2)

替换

中的元素名称
RelativePanel.AlignRightWith="logoBorder" 

通过ElementName绑定:

RelativePanel.AlignRightWith="{Binding ElementName=logoBorder}"