首页 > 解决方案 > WPF 如何使用 FactoryMethod 进行自定义控件

问题描述

.NET 4.7.2

我有一个包含自定义文本框的简单用户控件。我试图只在 Xaml 中定义接口,并通过指定 FactoryMethod 创建自定义 TextBox 的实例。

<UserControl x:Class="MyProject.TestView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"             
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:MyProject"
         mc:Ignorable="d" 
         d:DesignHeight="450" d:DesignWidth="800">

<Grid>
    <local:IInterfaceTextBox x:FactoryMethod="local:Factories.CreateInterfaceTextBox" x:Arguments="{x:Null}"  Text="{Binding Text}" CustomText="{Binding CustomText}"   />
</Grid>

工厂类:

namespace MyProject
{
    public class Factories
    {
        public static IInterfaceTextBox CreateInterfaceTextBox() => new InterfaceTextBox();
    }
}

第一个错误: “http://schemas.microsoft.com/winfx/2006/xaml”命名空间中不存在属性“FactoryMethod”。

当我设置 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 错误消息说在http://schemas.microsoft.com/winfx/2009/xaml中找不到 UserControl

有谁知道如何解决这个问题?

以防万一您想知道,为什么我首先要尝试这样做……我对新事物感到好奇:-)

标签: c#wpfinterfacefactory

解决方案


推荐阅读