Avoid XAML Designer error with custom controls

半腔热情 提交于 2019-12-11 04:19:37

问题


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

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.

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.

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.

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.

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?

Thanks!

Sergio


回答1:


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

Just use this code

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


来源:https://stackoverflow.com/questions/28821718/avoid-xaml-designer-error-with-custom-controls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!