简体   繁体   English

是否可以为WPF和Silverlight编译相同的控件?

[英]Is it possible to compile the same control for both WPF and Silverlight?

I have a complex control for Silverlight, and I need to have the same functionality in WPF. 我对Silverlight有一个复杂的控件,我需要在WPF中具有相同的功能。 Any way to share the codebase? 有没有办法分享代码库?

There are really three aspects that would need to be shared: 实际上有三个方面需要分享:

  1. Code files (such as *.cs *.vb) 代码文件(例如* .cs * .vb)
  2. XAML files (including themes) XAML文件(包括主题)
  3. Project files (such as *.csproj and *.vbproj) 项目文件(例如* .csproj和* .vbproj)

As Jaroslav pointed out, you can use conditional complication for code files, which is supported by C# and VB.Net . 正如Jaroslav指出的那样,您可以对C#VB.Net支持的代码文件使用条件复杂。 Keep in mind that Silverlight projects will by default define the SILVERLIGHT symbol, so you can use that in your conditional statements. 请记住,Silverlight项目默认定义SILVERLIGHT符号,因此您可以在条件语句中使用它。

Another trick for code files is to use partial classes . 代码文件的另一个技巧是使用部分类 This allows you to put entire blocks of code that may only apply to Silverlight or WPF (but not both) in a single file. 这允许您将可能仅适用于Silverlight或WPF(但不是两者)的整个代码块放在单个文件中。 Then selectively include that file in your project. 然后有选择地在项目中包含该文件。

Xaml files are a little tougher, as there are several things supported by WPF that are not supported by Silverlight (such as custom MarkupExtensions, etc). Xaml文件有点难度,因为Silverlight不支持WPF支持的一些内容(例如自定义MarkupExtensions等)。 In practice, I simply duplicate the XAML files and merge as needed. 在实践中,我只是复制XAML文件并根据需要合并。

Project files must be maintained manually, which isn't that big of a hassle. 项目文件必须手动维护,这不是一件容易的事。

I have written a blog article about sharing .xaml files. 我写了一篇关于共享.xaml文件的博客文章 The idea is to create a proxy control in your source code and use that control in .xaml : 我们的想法是在源代码中创建代理控件,并在.xaml使用该控件:

namespace UnifiedXaml
{
    public class MyWrapPanel: WrapPanel { }
}


<UserControl x:Class="UnifiedXaml.TestControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:ux="clr-namespace:UnifiedXaml">
    <ux:MyWrapPanel></ux:MyWrapPanel>
</UserControl>

If a control has different functionality in WPF and Silverlight, use styles . 如果控件在WPF和Silverlight中具有不同的功能,请使用样式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM