使用自定义控件避免 XAML 设计器错误 [英] Avoid XAML Designer error with custom controls

查看:25
本文介绍了使用自定义控件避免 XAML 设计器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个从另一个控件继承的自定义控件.我想设置这个控件的一些属性,所以我在构造函数里面加了这样的东西,例如:

Let's say that I have a custom control that inherits from another control. I want to set some properties of this control, so I add something like this inside the constructor, for example:

public class MyControl : Canvas
{
    public MyControl()
    {
        if (getSomeTestValueFromAppSettings())
        {
            this.Background = ColorConverter.MyStaticBrushProperty1;
        }
        else
        {
            this.Background = ColorConverter.MyStaticBrushProperty2;
        }
    }
}

现在,应用程序内一切正常,所以没有问题.关键是,如果我在控件构造函数中添加类似的东西,我会收到 XAML 设计器的错误,它告诉我它无法创建控件的实例.

Now, everything works fine inside the app, so no problems there. The point is that if I add something like this inside my control constructor, I get an error with the XAML designer, and it tells me it can't create an instance of the control.

没关系,因为当然构造函数正在尝试访问应用程序本地设置,而它不能在 XAML 设计器中执行此操作.

That's ok, since of course the constructor is trying to access the app local settings, and it can't do that inside the XAML Designer.

我目前正在使用它作为一种解决方法:我只是将我的所有 conde 包装在 try/catch 块中的构造函数中,如果我遇到异常(仅发生在 XAML 设计器中),我会直接忽略它.

I'm currently using this as a workaround: I simply wrap all my conde inside the constructor inside a try/catch block, and if I got an exception (that only happens inside the XAML Designer) I simply ignore it.

这样代码在手机上仍然可以正常工作,并且不会使 XAMl 设计器崩溃.不过,我不认为这是一个好的解决方案,我认为类构造函数中的 try/block 不是一种好的编程习惯.

This way the code stillworks fine on the phone, and it doesn't crash the XAMl Designer. I don't think that this is a good solution though, a try/block inside a class constructor is not something I think could be considered a good programming practice.

我希望有类似编译器指令"的东西,它告诉编译器什么时候它实际上不是在设备/模拟器上运行,而是在 XAML 设计器中运行,但我没有找到类似的东西.

I was hoping there was something like a "compiler directive" that tells the compiler when it's not actually running on a device/emulator, but just inside the XAML Designer, but I didn't find anything like that.

您有关于如何解决该问题的建议或其他更好的想法吗?

Do you have suggestions or other better ideas on how to solve that problem?

谢谢!

塞尔吉奥

推荐答案

对于这种情况,实际上有一个内置方法.

There is actually a build-in method for situations like this.

只需使用此代码

    if (DesignerProperties.GetIsInDesignMode(this))
    {
        // Design-mode specific functionality
    }

这篇关于使用自定义控件避免 XAML 设计器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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