【问题标题】:How to use Xaml inheritance in WinUI 3?如何在 WinUI 3 中使用 Xaml 继承?
【发布时间】:2021-12-19 21:02:10
【问题描述】:

answers like this 看来,xaml 继承似乎适用于 WPF 和 UWP。

它适用于 WinUI 3 吗?

使用这样的代码:

    <local:YourBaseClass x:Class="MyApp.ChildClass"
        ...
        xmlns:local="clr-namespace:MyApp">
    </local:YourBaseClass>

我得到错误:

Error WMC0001 Unknown type 'YourBaseClass' in XML namespace 'clr-namespace:MyApp'

【问题讨论】:

    标签: xaml winui-3


    【解决方案1】:

    它适用于 WinUI 3 吗?

    是的。几乎一模一样。

    1. 创建继承自Microsoft.UI.Xaml.Window的基类:

       public class YourBaseClass : Microsoft.UI.Xaml.Window
       {
           public YourBaseClass() : base()
           {
               Title = "Title...";
           }
       }
      
    2. 修改 MainWindow.xaml.cs 以从新的基类继承:

       public sealed partial class MainWindow : YourBaseClass
       {
           public MainWindow()
           {
               this.InitializeComponent();
           }
      
           private void myButton_Click(object sender, RoutedEventArgs e)
           {
               myButton.Content = "Clicked";
           }
       }
      
    3. 修改MainWindow.xaml中的根元素:

       <local:YourBaseClass
           x:Class="WinUI3App.MainWindow"
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
           xmlns:local="using:WinUI3App"
           xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
           xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
           mc:Ignorable="d">
      
           <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
               <Button x:Name="myButton" Click="myButton_Click">Click Me</Button>
           </StackPanel>
       </local:YourBaseClass>
      

    【讨论】:

    • 啊,关键是用xmlns:local="using:WinUI3App"而不是xmlns:local="clr-namespace:WinUI3App"。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-10-23
    • 2022-07-18
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    相关资源
    最近更新 更多