You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何构建WINUI控件库?求自定义控件跨应用共享的实现方案

如何创建可共享的WinUI自定义用户控件库

WinUI确实没有官方的"User Control Library"模板,但可以通过以下步骤手动创建可共享的控件库:

1. 创建基础项目

新建一个Windows 运行时组件项目(这是WinUI控件库的基础载体,因为WinUI控件基于WinRT)。

2. 配置项目文件

修改项目的.csproj文件,添加WinUI依赖并调整配置:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <!-- 目标框架选择支持WinUI的Windows SDK版本,比如19041及以上 -->
    <TargetFramework>net6.0-windows10.0.19041.0</TargetFramework>
    <Platforms>x64;x86;ARM64</Platforms>
    <Nullable>enable</Nullable>
    <!-- 启用WinUI支持 -->
    <UseWinUI>true</UseWinUI>
    <OutputType>Library</OutputType>
    <RootNamespace>YourControlLibrary</RootNamespace>
  </PropertyGroup>

  <ItemGroup>
    <!-- 添加WinUI包引用,版本选择最新稳定版 -->
    <PackageReference Include="Microsoft.UI.Xaml" Version="2.8.1" />
  </ItemGroup>
</Project>

3. 添加自定义用户控件

在项目中右键选择添加 -> 新建项,选择User Control (WinUI 3),之后就可以像WPF一样编写控件的XAML和后台逻辑:

示例自定义按钮控件

XAML代码:

<UserControl
    x:Class="YourControlLibrary.CustomButton"
    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">

    <Button x:Name="InnerButton" 
            Background="DarkBlue" 
            Foreground="White"
            Click="InnerButton_Click">
        <ContentPresenter Content="{Binding Content, RelativeSource={RelativeSource Mode=TemplatedParent}}" />
    </Button>
</UserControl>

C#后台代码:

using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;

namespace YourControlLibrary;

public sealed partial class CustomButton : UserControl
{
    public static readonly DependencyProperty ContentProperty =
        DependencyProperty.Register(nameof(Content), typeof(object), typeof(CustomButton), new PropertyMetadata(null));

    public object Content
    {
        get => GetValue(ContentProperty);
        set => SetValue(ContentProperty, value);
    }

    public CustomButton()
    {
        this.InitializeComponent();
    }

    private void InnerButton_Click(object sender, RoutedEventArgs e)
    {
        Click?.Invoke(this, e);
    }

    public event RoutedEventHandler? Click;
}

4. 在其他WinUI应用中共享使用

  • 直接添加项目引用:在目标WinUI应用中右键项目 -> 添加 -> 项目引用,选择你的控件库项目。
  • 打包为NuGet包:在项目属性的NuGet包标签页配置包信息,然后运行dotnet pack命令生成NuGet包,即可在多个应用中通过NuGet引用。

内容的提问来源于stack exchange,提问作者fuqi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 22:05:29