UserControl在Xpl中定义Wpf

时间:2018-01-19 08:42:46

标签: c# wpf xaml wpf-controls

在UserControl标签中,我如何声明命名空间,类名及其继承类名。如果我输入Namespacename.WindowLevelGraphControlxaml.cs中显示错误,我在其中定义类WindowLevelGraphControl : UserControl。 这个错误是Class更多不同基类的定义。

<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>

如果我在类中删除名称空间名称显示错误,就像没有定义intialcomponent();

等待你的指导。感谢

2 个答案:

答案 0 :(得分:0)

开始通过像往常一样添加一个名为WindowLevelGraphControl的UserControl 这应该在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

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

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 

答案 1 :(得分:0)

得到了你的问题。例如,您已创建了一个类

    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步

您必须使用xmll添加xml命名空间 XMLNS。 xmlns应该引用您正在使用的控件的基类。 例如,类测试的基类是 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现在你应该能够编译你的代码了。