WPF的自定义控件无法识别 [英] wpf custom control not recognized

查看:506
本文介绍了WPF的自定义控件无法识别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次尝试自定义控件,但进展不顺利。我有一个从Canvas派生的自定义图形控件。

This is my first foray into custom controls, and it's not going well. I have a custom graph control derived from Canvas.

namespace Grapher2 {
    public class SeriesManager : Canvas {
        public SeriesManager() {
            ...
        }
    }
}

与我的应用相同的项目和名称空间。我尝试按如下所示在XAML中添加对该控件的引用:

It's defined in the same project and namespace as my app. I tried adding a reference to the control in XAML as follows:

<Window x:Class="Grapher2.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:graph="clr-namespace:Grapher2"
Title="Grapher" Width="800" Height="600">

<StackPanel Name="container"  Width="700" Height="500">
    <graph:SeriesManager Name="seriesManager" Width="700" Height="500" />
</StackPanel>

但是当我尝试引用时在窗口代码背后的控件名称 seriesManager中,我得到名称 seriesManager在当前上下文中不存在。

But when I try to reference the control name "seriesManager" in the code-behind for the Window, I get "The name 'seriesManager' does not exist in the current context."

此外,XAML编辑器将不会渲染Window,从而给出了巨大的堆栈跟踪,并显示错误: Assembly'PresentationFramework中的类型'MS.Internal.Permissions.UserInitiatedNavigationPermission' ,版本= 3.0.0.0,文化=中立,PublicKeyToken = 31bf3856ad364e35'未标记为可序列化。

Furthermore, the XAML editor will not render the Window, giving a huge stack trace with the error: "Type 'MS.Internal.Permissions.UserInitiatedNavigationPermission' in Assembly 'PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' is not marked as serializable."

我想该解决方案对于完成自定义操作的任何人来说都非常简单控件。

I imagine the solution is something stupidly simple for anyone who's done custom controls. But I'm stumped.

推荐答案

您在xaml中尝试了x:Name = seriesManager吗?

did you try x:Name="seriesManager" in your xaml?

编辑:这可能不是您看到xaml无法渲染的问题。我猜想一旦让xaml在设计器中呈现...后面的代码将更好地工作。

This may not be the issue seeing how you said your xaml isn't rendering. I'm guessing once you get the xaml to render in the designer... the code behind will work better.

编辑2:每当我遇到问题时设计器渲染,这是因为我正在自定义控件的构造函数中执行某些操作。检查您的SeriesManager,以查看您是否在其构造函数中执行了导致问题的操作。也许您引用的是尚不存在的东西。如果构造函数中确实包含其他代码,请考虑将其移至UserControl_Loaded事件。

Edit 2: Whenever I've had a problem with the designer rendering, it's because I'm doing something in the constructor of my custom control. Check your SeriesManager to see if you are doing something in its constructor that is causing a problem. Maybe you are referencing something that doesn't exist yet. If you do have extra code in your constructor, consider moving it to the UserControl_Loaded event.

这篇关于WPF的自定义控件无法识别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆