Design-Time Resourcedictionaries - c#

I have created something like this and this.
In effect I have a dll which supplies me with a "styler" for my application - it contains all my basic styles as well as a factory to call StylerFactory.DefaultStyler.ApplyStyles(this) on an Application - which merges the supplied ResourceDictionaries with the existing. This way I don't need all the basic styles in my components, nor do I need explicit references to my sesource-xaml-files.
Now - while this is working real good. The Styles are (obviously) not visible during design-time
To my questions:
Was that approach wise, or would it have been better to deploy xaml-resources and use them in every app/window/control ?
Does someone see any possibility to apply my styles to the design-time display of VS2008 ?

In my opinion, it's an acceptable approach. The reason being, I haven't seen a better method.
In my own cases, I've loaded resource dictionaries at runtime using the code I described here, which I would assume would work for loading resources from other assemblies as well. The drawback is that the designer will not run this code first, meaning no style is applied by default, what you're experiencing.
To counteract this, I added a default <ResourceDictionary.MergedDictionaries> definition in each of my <Window.Resources> that I needed to edit at design-time. While this ends up being a bit redundant, this allowed me to have a working design-time Window while the proper MergedDictionary can be loaded later during runtime. Perhaps you can use this to find a better method.

Related

Is there a general way to avoid exceptions when editing XAML? [duplicate]

I am working without expression blend and just using the XAML editor in vs2010. The wisdom of this aside, I am increasingly seeing a need for design-time data binding. For simple cases, the FallbackValue property works very nicely (Textboxes and TextBlocks, etc). But especially when dealing with ItemsControl and the like, one really needs sample data to be visible in the designer so that you can adjust and tweak controls and data templates without having to run the executable.
I know that ObjectDataProvider allows for binding to a type, and thus can provide design-time data for visualizing, but then there is some juggling to allow for the real, run-time data to bind without wasting resources by loading loading both the design time, dummied data and the runtime bindings.
Really what I am wanting is the ability to have, say, "John", "Paul", "George", and "Ringo" show up in the XAML designer as stylable items in my ItemsControl, but have real data show up when the application runs.
I also know that Blend allows for some fancy attributes that define design time binding data that are effectively ignored by WPF in run-time conditions.
So my questions are:
1. How might I leverage design-time bindings of collections and non-trivial data in the visual studio XAML designer and then swap to runtime bindings smoothly?
2. How have others solved this design-time vs. runtime data problem? In my case, i cannot very easily use the same data for both (as one would be able to with, say, a database query).
3. Are their alternatives to expression blend that i could use for data-integrated XAML design? (I know there are some alternatives, but I specifically want something I can use and see bound sample data, etc?)
Using VS2010 you can use Design-Time attributes (works for both SL and WPF). I usually have a mock data-source anyway so it's just a matter of:
Adding the namespace declaration
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
Adding the mock data context to window/control resources
<UserControl.Resources>
<ViewModels:MockXViewModel x:Key="DesignViewModel"/>
</UserControl.Resources>
Setting design-time data context
<Grid d:DataContext="{Binding Source={StaticResource DesignViewModel}}" ...
Works well enough.
As an amalgam of Goran's accepted answer and Rene's excellent comment.
Add the namespace declaration.
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
Reference your design time data context from code.
<Grid d:DataContext="{d:DesignInstance Type=ViewModels:MockXViewModel, IsDesignTimeCreatable=True}" ...
I use this approach for generating design time data with .NET 4.5 and Visual Studio 2013.
I have just one ViewModel.
The view model has a property IsInDesignMode which tells whether design mode is active or not (see class ViewModelBase).
Then you can set up your design time data (like filling an items control) in the view models constructor.
Besides, I would not load real data in the view models constructor, this may lead to issues at runtime, but setting up data for design time should not be a problem.
public abstract class ViewModelBase
{
public bool IsInDesignMode
{
get
{
return DesignerProperties.GetIsInDesignMode(new DependencyObject());
}
}
}
public class ExampleViewModel : ViewModelBase
{
public ExampleViewModel()
{
if (IsInDesignMode == true)
{
LoadDesignTimeData();
}
}
private void LoadDesignTimeData()
{
// Load design time data here
}
}
Karl Shifflett describes an approach that ought to work equally well for VS2008 and VS2010:
Viewing Design Time Data in Visual Studio 2008 Cider Designer in WPF and Silverlight Projects
Laurent Bugnion has a similar approach that focuses on Expression Blend. It might work for VS2010, but I haven't confirmed this yet.
Simulating data in design mode in Microsoft Expression Blend
Maybe the new design-time features of Visual Studio 2010 and Expression Blend 4 are an option for you.
How it works is shown in the BookLibrary sample application of the WPF Application Framework (WAF). Please download the .NET4 version.
Similar to the top rated answer, but better in my opinion: You can create a static property to return an instance of design data and reference it directly from XAML like so:
<d:UserControl.DataContext>
<Binding Source="{x:Static designTimeNamespace:DesignTimeViewModels.MyViewModel}" />
</d:UserControl.DataContext>
This avoids the need to use UserControl.Resources. Your static property can function as a factory allowing you to construct non-trivial data types - for example if you do not have a default ctor, you can call a factory or container here to inject in appropriate dependencies.
Using Visual Studio 2017 I have been trying to follow all of the guides and questions such as this and I was still facing a <ItemsControl> which simply did not execute the code I had inside the constructor of a DesignFooViewModel which inherits from FooViewModel. I confirmed the "did not execute" part following this "handy" MSDN guide (spoiler: MessageBox debugging). While this is not directly related to the original question, I hope it will save others a lot of time.
Turns out I was doing nothing wrong. The issue was that my application needs to be built for x64. As the Visual Studio is still in 2018 a 32-bit process and apparently cannot spin a 64-bit host process for the designer part it cannot use my x64 classes. The really bad thing is that there are no errors to be found in any log I could think of.
So if you stumble upon this question because you are seeing bogus data in with your design time view model (for example: <TextBlock Text="{Binding Name}"/> shows up Name no matter you set the property to) the cause is likely to be your x64 build. If you are unable to change your build configuration to anycpu or x86 because of dependencies, consider creating a new project which is fully anycpu and does not have the dependencies (or any dependencies). So you end up splitting most or all but the initialization parts of the code away from your "WPF App" project into a "C# class library" project.
For the codebase I am working on I think this will force healthy separation of concerns at the cost of some code duplication which is probably net positive thing.
I liked jbe's suggestion, specifically to look at how they do it in the WAF framework sample apps - they use separate mock/sample view models in a DesignData folder and then have a line like this in the XAML:
mc:Ignorable="d"
d:DataContext="{d:DesignInstance dd:MockHomeViewModel, IsDesignTimeCreatable=True}"
(where dd points to the .DesignData namespace where MockHomeViewModel lives)
It's nice and simple (which I like!) and you can inherit from the real VMs and just provide dummy data. It keeps things separate as you don't need to pollute your real VMs with any design time only code. I appreciate things might look quite different for a large project utilising IOCs etc but for small projects it works well.
But as joonas pointed out, it seems not to work with x64 builds in VS2017 and this still seems to be the case with VS2019 (I'm using V2019 16.6 Community edition). It's not fiddly to get working to start off with but can cause some head scratching when after making a change (or as is usually the case, several changes!) it suddenly stops working.
For anybody trying it, I would recommend creating a new simple WPF project (say one view, one view model, one mock vm) and play around with it; get it working and then break it. I found sometimes, no amount of solution cleans and rebuilds would fix it, the only thing that worked was closing VS down and restarting, and suddenly my design time data came back!

Summary of WPF designer limitations and rules for WYSIWYG view creation?

For WPF/Silverlight/XAML4Win8/WP8/whathaveyou, the visuals are created by (I believe) newing up an instance of the base class that your custom view (window/page/usercontrol/whathaveyou) is derived from, and then applying your XAML after the fact.
If I'm not mistaken this means codebehind in the type's constructor is lost. Is there a way to execute design-time object creation logic in the view itself? More importantly is there a good summary online somewhere of how the Cider/Blend designers actually create the WYSIWYG views at design time? I seem to recall some documentation on this somewhere (Expression Studio docs maybe?) But I can't find them for the life of me.
http://msdn.microsoft.com/en-us/library/ff602274(v=vs.95).aspx
The above link applies to Silverlight, but pretty sure most if not all applies to WPF as well.
You can instantiate a designer DataContext.
<Grid x:Name="LayoutRoot" Background="White"
d:DataContext="{d:DesignInstance Type=local:Customer}">
One limitation is that it requires you to have a default constructor. Here is an answer I found to get around it.
How to use d:DesignInstance with types that don't have default constructor?.
Best would be to subclass the data you are coding against and have it do any necessary initializing. Luckily everything you are defining is purely for the designing and has no effect on what objects you are actually working with at runtime.
Unfortunately I do not have answers for the rest of the questions.
what kind of stuff do you need to do in the constructor?
Could you do it by adding either dependency or attached properties with DependencyPropertyChanged hooks and setting values in the xaml?
Then you’d still get your code executing, but not the constructor?

MEF - use the same plugins several times

I've read MEF documentation on Codeplex and I'm trying to figure out how to accomplish my task:
I would like to build an application framework that has standard components that can be used to do some common work (like displaying a list of records from a database). Plugins should be reused many times with different configuration each time. (eg. I have 5 windows in an application where I display record lists, each with different type of entity, different columns, each one should have it's own extension points like for displaying record details that should be satisfied with a different copy of another common plugin).
Is MEF suitable for such a scenario? How should I define contracts? Should I use metadata? Can I define relationships using configuration files?
Yes, you can use MEF. MEF supports NonShared instantiation of objects using the PartCreationPolicy attribute:
[PartCreationPolicy(CreationPolicy.NonShared)]
More information on this here.
Personally I'd do the wiring and configuration after the importing of the component on the target. However I am not sure how generic you want your application to be, if you are making a 'framework' to do certain solutions in I can imagine you want the configuration to be separate. You can go all-over-board and make an ISuperDuperGridConfiguration and import these on the constructor [ImportingConstructor] of your grid plugin. From within your target (where the grids get imported) set the location of the grid to the grid plugin (like main grid, side grid) and use the data stored in ISuperDuperGridConfiguration to further config the grid plugin itself.
However, you can easily go 'too far' with MEF, depending on your goals. We have a completely MEF componentized UI for an application with customized needs for every single customer. Sometimes I have the urge to put single buttons from the ribbon in a MEF extension.
As you can see, depending on your needs, you can and sometimes will go too far.
I don't think you'd need metadata especially in your case, but maybe someone else can share a different opinion on this ;-).
I hope this answers your question, if not please comment so I can highlight more aspects. All in all using MEF has been very positive for us, and we are using it far beyond a 'hello world' so to say. So at least you have that!

DesignerAttribute in WPF?

Is it possible in WPF to provide an alternate class which should be used as the control to show in the designer instead of the control itself, just like DesignerAttribute does for WinForms?
EDIT:
What I'm looking for is what happens with e.g. the ReportViewer class does. This class has an associated class ReportViewerDesigner which is used in the designer instead of the ReportView class itself.
You can manipulate the Metadata Store; since WPF separates the designer metadata into a separate assembly as noted in the MSDN.
In the System.ComponentModel
framework, a designer type is
associated with its corresponding
component through the
DesignerAttribute metadata attribute.
This means the relationship is
established at compile time, forcing a
hard-coded dependency between the
component's run-time and design-time
behavior. To attach a different
designer, you must change the
DesignerAttribute declaration and
recompile the component's code base.
In the WPF Designer, designer metadata
is factored into a separate assembly,
physically decoupling it from the
run-time implementation. This freedom
means that different tools can present
completely different design
experiences for the same run-time
type. For more information, see
Metadata Store.
A concrete example of this is the VS designer versus the Expression Blend designer.
EDIT:
As noted in the comments section they are fundamentally different approaches. It is not a 1:1 by any means; just as is with a WinForms versus WPF approach to building an application. If you are looking for an elusive attribute which will simply use a differing class as the designer representation; it does not exist. There are certainly ways to achieve what you want and allow the designer to display a given control in a myriad of ways but the approach is not like that of WinForms.
How To: Use the Metadata Store
WPF Designer Extensibility
Architecture (look at Designer Instance Creation)

Managing loosely coupled assembly references incurred through usage of the 'Designer' attribute

We build a lot of components, WinForms, Workflow activities etc, and something that we use a lot is the 'Designer' attribute.
The general practice during initial development is, the Designer attribute is used with the [Designer(typeof(DesignerType))] style to get things working - then later, this is converted to [Designer("AssemblyQualifiedTypeName")], which allows the designer DLL to be removed from the component's reference list - this removes the need for the component consumer to have to deploy the designer DLL with their product.
This practice of splitting the design-time, and run-time code into two seperate DLLs is common practice, and one that I am a proponent of.
A negative side effect, is the 'assembly qualified type name' will include the assembly version of the designer dll, so when the version is incremented, one must perform a 'search and replace' across the product to ensure they have updated all the 'loose references' to this designer.
Finally, my question:
Can anyone reccomend a best practice that doesnt rely on 'search and replace', which can manage all these references, to ensure they are always up to date?
We often get a lazy developer forgetting to update the reference string, resulting in a new version of the component linking to the previous version of the designer DLL - which of course doesnt get deployed, so design-time support is lost.
Perhaps some form of pragmas, macros, build script, magic attributes, I dont know, but there must be a better way of doing this.
Anyone? (thanks)
Why not create a single designer that uses something like the Managed Addin Framework or Activator.CreateInstance internally to pick and show a designer? With this technique, the Designer attribute would never have to change...
Do it like Microsoft does. Take a look at AssemblyRef class (System.Windows.Forms.dll) in Reflector.

Categories