UserControl Define in Xaml of Wpf



在用户控制标记中,如何声明命名空间,类名及其继承类名。 如果我输入Namespacename.WindowLevelGraphControl在我定义类的xaml.cs中显示错误,例如WindowLevelGraphControl : UserControl. 此错误是类是不同基类的更多定义。

<UserControl x:Class="WindowLevelGraphControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid Height="0" Width="0">
</Grid>

如果我删除命名空间名称,则在类中显示错误,例如不定义初始组件();

等待您的指导。谢谢

像往常一样添加一个名为 WindowLevelGraphControl 的用户控件 这应该在 WindowLevelGraphControl.xaml 中生成

<UserControl x:Class="WindowLevelGraphNS.WindowLevelGraphControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

并在 WindowLevelGraphControl.xaml 中.cs

public partial class WindowLevelGraphControl : UserControl

现在在本地命名空间中定义 yout 基类,即WindowLevelGraphNS,它继承了UserControl,但也包括您希望对其子级可用的自定义代码

namespace WindowLevelGraphNS
{
public class BaseClass : UserControl
{

然后,可以通过编辑如下所示的 XAML 文件来指定上面定义的用户控件继承此类

<local:BaseClass x:Class="WindowLevelGraphNS.WindowLevelGraphControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WindowLevelGraphNS"

然后后端文件 .xaml.cs像这样

public partial class WindowLevelGraphControl: BaseClass 

有你的问题。例如,您创建了一个类

namespace TestNamespace
{
public partial class Test :ModelBase
{
public Test()
{
InitializeComponent();
}
}
}
namespace TemplateLoader.Lib.Base
{
public class ModelBase : DependencyObject, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}

您正在尝试在您的 xaml 中引用它。

步骤 1

您必须使用 xmlns。xmlns 应引用正在使用的控件的基类。 例如,这里的类 Test的基类是ModelBase

因此,您的 xml 应该包含类ModelBase的引用。

在您的 xaml 中添加此内容:-

xmlns:modelbase="clr-namespace:TemplateLoader.Lib.Base;assembly=TemplateLoader.Lib"

这是因为类ModelBase被写成命名空间TemplateLoader.Lib.Base

步骤 2

添加引用后,可以使用命名空间在 xaml 中使用类 Test。

<modelbase:ModelBase x:Class="TestNamespace.Test"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:modelbase="clr-namespace:TemplateLoader.Lib.Base"
mc:Ignorable="d" >
</modelbase:ModelBase>

如果它不编译并说分部类不能有不同的声明。然后你需要重新检查该行:-

x:Class 应该是类的全名。这是TestNamespace.Test 现在你应该能够编译你的代码了。

最新更新