简体   繁体   中英

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. Any way to share the codebase?

There are really three aspects that would need to be shared:

  1. Code files (such as *.cs *.vb)
  2. XAML files (including themes)
  3. Project files (such as *.csproj and *.vbproj)

As Jaroslav pointed out, you can use conditional complication for code files, which is supported by C# and VB.Net . Keep in mind that Silverlight projects will by default define the SILVERLIGHT symbol, so you can use that in your conditional statements.

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. 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). In practice, I simply duplicate the XAML files and merge as needed.

Project files must be maintained manually, which isn't that big of a hassle.

I have written a blog article about sharing .xaml files. The idea is to create a proxy control in your source code and use that control in .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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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