【发布时间】:2019-07-31 15:18:42
【问题描述】:
我正在尝试做的事情:
创建消费者可以像 UWP 页面一样使用的自定义页面控件,但是,它还会在消费者内容旁边显示它自己的自定义内容。
我尝试了什么:
创建一个新控件,继承自 Page
创建一个从页面继承的模板化控件
创建包含页面的控件
在我的自定义页面中设置
ContentProperty属性并绑定到它
有什么问题?
当我尝试创建一个同时具有xaml 和xaml.cs 文件的控件时,该文件继承自Page,我在子类控件内的随机控件上得到InvalidCastExceptions。
示例:
TestPage.xaml
<Page
x:Class="ControlSandbox.TestPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:uwp_toolkit="using:Microsoft.Toolkit.Uwp.UI.Controls"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Page.Content>
<ContentPresenter Content="{Binding}" />
</Page.Content>
<Page.BottomAppBar>
<AppBar Background="Transparent" x:Name="appbar" IsOpen="True">
<uwp_toolkit:InAppNotification x:Name="note">
<StackPanel>
<TextBlock>HEADER!</TextBlock>
<TextBlock>Message</TextBlock>
<StackPanel Orientation="Horizontal">
<Button>OK</Button>
<Button>Cancel?</Button>
</StackPanel>
</StackPanel>
</uwp_toolkit:InAppNotification>
</AppBar>
</Page.BottomAppBar>
</Page>
TestPage.xaml.cs
public partial class TestPage : Page
{
public TestPage()
{
this.InitializeComponent();
}
public void ShowNotification()
{
appbar.IsOpen = true;
note.Show();
}
}
MainPage.xaml
<controlsandbox:TestPage
xmlns:controlsandbox="using:ControlSandbox" x:Class="ControlSandbox.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<Button Click="Button_Click">SHOW NOTIFICATION</Button>
</Grid>
</controlsandbox:TestPage>
MainPage.xaml.cs
public partial class MainPage : TestPage
{
public MainPage()
{
this.InitializeComponent();
}
private void Button_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
this.ShowNotification();
}
}
上面的代码导致InvalidCastException,我一辈子都找不到问题。
System.InvalidCastException: '无法转换类型的对象 'Windows.UI.Xaml.Controls.AppBar' 键入 'Windows.UI.Xaml.Controls.Button'。'
现在,如果我执行完全相同的代码,但都在 MainPage.xaml 而不是 TestPage.xaml 中,一切都会按预期工作
更新
所以我相信这是平台中的一个错误。这是我对这个问题所做的演示。请证明我错了,因为这将是一个真正的限制https://github.com/DotNetRussell/UWP_Page_Inheritance_Bug
更新
我为下面的答案添加了更改。似乎当我创建一个普通的模板化控件并将其放在一个普通的 uwp 页面上时,它工作正常。但是,当我创建模板化 Page 时,它会忽略我的模板。
更新
我认为这是平台中的一个错误。我在 github 上打开了一个问题 https://github.com/microsoft/microsoft-ui-xaml/issues/1075
【问题讨论】:
-
根据您的描述,您想自定义页面吗?
-
@NicoZhu-MSFT 是的,我想要一个自定义页面,它将消费者提供的内容与它自己的默认内容相结合。想象一个控件,默认情况下具有其他元素,如导航窗格、通知栏、上下文栏和其他内容。然后你给它你的内容,它把它放在中间。