Design time data in WPF - wpf

[using vs2010 & expression blend v4]
Hi - trying to load up some design time data in WPF and Blend, using Josh Smith's concept here: http://joshsmithonwpf.wordpress.com/2010/04/07/assembly-level-initialization-at-design-time/
e.g.
[AttributeUsage(AttributeTargets.Assembly)]
public class DesignTimeBootstrapperAttribute : Attribute
{
public DesignTimeBootstrapperAttribute(Type type)
{
var dep = new DependencyObject();
Debug.WriteLine("here..?");
if (DesignerProperties.GetIsInDesignMode(dep))
{
// TODO: Design-time initialization…
IBootstrapper instance = Activator.CreateInstance(type) as IBootstrapper;
if (instance != null)
{
instance.Run();
}
}
}
}
With my attribute here in AssemblyInfo.cs, where AppBootstrapper extends MefBootstrapper.
[assembly: AssemblyCopyright("Copyright © 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: DesignTimeBootstrapper(typeof(AppBootstrapper))]
I don't want to use the Blend sample data, a) as it doesn't seem to create data for ObservableCollection and b) I'm in design mode by definition, so things will change quite a lot, but my 'generated data' will not.
Anyway, nothing seems to be happening.
Q1: How is it possible to debug the design time initialisation of my bootstrapper?
Q2: Do I need additional blend namespaces/ attributes etc in my View XAML?
(In my bootstrapper I'm just registering a different module where I want to replace RunTimeService with a DesignTimeService, exporting the IService interface).
TIA

To debug this:
Open your project in VS2010
Set a breakpoint in the assembly attribute constructor
Start a new instance of Blend 4
From VS2010 use Debug -> Attach to Process: and choose Blend
Switch to Blend and open your project
Open a XAML file that references your sample data
Also, any Debug.WriteLine should appear in the VS2010 output window.
If you can't get the attribute method to work (I haven't tried it myself), you can use this method (which I have used) from MVVM Light:
private bool? _isInDesignMode;
public bool IsInDesignMode
{
get
{
if (!_isInDesignMode.HasValue)
{
var prop = DesignerProperties.IsInDesignModeProperty;
_isInDesignMode =
(bool)DependencyPropertyDescriptor
.FromProperty(prop, typeof(FrameworkElement))
.Metadata.DefaultValue;
}
return _isInDesignMode.Value;
}
}

Related

How to create Visual Studio 2012 WPF custom designer/editor [duplicate]

Im trying to write a editor extension for Visual Studio. I have the downloaded VS SDK and created a new Visual Studio Package project. But the dummy control created for me is a Windows Forms control and not a WPF control. I'm trying to replace it with a WPF-control but not doing so well. Is this possible anyhow?
Another related question: Is it only possible to write text-editors? What I really want is a editor that looks more like a form with many different fields. But it doesn't seem to be what this is made for? There are a lot of interfaces on the EditorPane that imply a text-editor model only.
Ideally I want a editor much like the resx-editor where the file being edited has xml-content and the editor-ui is not a single textbox and where a generated cs-file is being outputted as a sub-file. Is this possible to do with editor extensions?
This is explained in detail here: WPF in Visual Studio 2010 – Part 4 : Direct Hosting of WPF content
So, if you use the standard Extensibility / Custom Editor sample that comes with the Visual Studio SDK, what you can do to test it is this:
1) Modify the provided EditorFactory.cs file like this:
// Create the Document (editor)
//EditorPane NewEditor = new EditorPane(editorPackage); // comment this line
WpfEditorPane NewEditor = new WpfEditorPane(); // add this line
2) create for example a WpfEditorPane.cs file like this:
[ComVisible(true)]
public class WpfEditorPane : WindowPane, IVsPersistDocData
{
private TextBox _text;
public WpfEditorPane()
: base(null)
{
_text = new TextBox(); // Note this is the standard WPF thingy, not the Winforms one
_text.Text = "hello world";
Content = _text; // use any FrameworkElement-based class here.
}
#region IVsPersistDocData Members
// NOTE: these need to be implemented properly! following is just a sample
public int Close()
{
return VSConstants.S_OK;
}
public int GetGuidEditorType(out Guid pClassID)
{
pClassID = Guid.Empty;
return VSConstants.S_OK;
}
public int IsDocDataDirty(out int pfDirty)
{
pfDirty = 0;
return VSConstants.S_OK;
}
public int IsDocDataReloadable(out int pfReloadable)
{
pfReloadable = 0;
return VSConstants.S_OK;
}
public int LoadDocData(string pszMkDocument)
{
return VSConstants.S_OK;
}
public int OnRegisterDocData(uint docCookie, IVsHierarchy pHierNew, uint itemidNew)
{
return VSConstants.S_OK;
}
public int ReloadDocData(uint grfFlags)
{
return VSConstants.S_OK;
}
public int RenameDocData(uint grfAttribs, IVsHierarchy pHierNew, uint itemidNew, string pszMkDocumentNew)
{
return VSConstants.S_OK;
}
public int SaveDocData(VSSAVEFLAGS dwSave, out string pbstrMkDocumentNew, out int pfSaveCanceled)
{
pbstrMkDocumentNew = null;
pfSaveCanceled = 0;
return VSConstants.S_OK;
}
public int SetUntitledDocPath(string pszDocDataPath)
{
return VSConstants.S_OK;
}
#endregion
}
Of course, you will have to implement all the editor logic (add interfaces, etc.) to mimic what's done in the Winforms sample, as what I provide here is really the minimal stuff for pure demonstration purposes.
NOTE: this whole "Content" thing only works starting with Visual Studio 2010 (so you need to make sure your project references Visual Studio 2010 assemblies, which should be the case if you start a project from scratch using Visual Studio 2010). Hosting WPF editors within Visual Studio 2008 is possible using System.Windows.Forms.Integration.ElementHost.
I'm not sure if the above is possible but a quick search did turn up this:
http://karlshifflett.wordpress.com/2010/03/21/visual-studio-2010-xaml-editor-intellisense-presenter-extension/
and this:
http://blogs.msdn.com/b/visualstudio/archive/2009/12/09/building-and-publishing-an-extension-for-visual-studio-2010.aspx
Failing that, could you not host a WPF control inside the winforms control using ElementHost? I know its a lame workaround but might allow you to develop in your favourite toolkit while you find a more permanent solution.
Best regards,
There is a sample VS Extension Package application source code on MSDN: Designer View Over XML Editor.
Description from site:
This Sample demonstrates how to create an extension with a WPF-based Visual Designer for editing XML files with a specific schema (XSD) in coordination with the Visual Studio XML Editor.
Admittedly solution is dedicated for VS2010 Extension Package, however it can be simply converted and attuned to VS2012 format - Target platform should be change to .NET 4.5, thereafter some references to VS2012 assemblies (v.11.0) should be added to build and run startup project:
Microsoft.VisualStudio.Shell.11.0.dll
Microsoft.VisualStudio.Shell.Immutable.11.0.dll
Microsoft.VisualStudio.Shell.Interop.11.0
In case of problems, please visit Q & A section of the site.

WPF: Binding TreeView in MVVM way step by step tutorial

See the next post. This original one question content has been removed, as doesn't have any sense. Briefly, I asked how to bind XML (which I generated by mistake while parsing DLL assembly) to TreeView using XmlDataProvider in MVVM way. But later I understood that this approach was wrong, and I switched to generation of data entity model (just write classes which represent all the entities I would like to expose in the tree) instead of XML.
So, the result in the next post. Currently from time to time I update this "article", so F5, and
Enjoy reading!
Introduction
The right way I had found reading this article
It's a long story, most of you just can skip it :) But those, who want to understand the problem and solution, must read this all !
I'm QA, and some time ago had become responsible for Automation of the product I clicks. Fortunately, this automaton takes place not in some Testing Tool, but in Visual Studio, so it is maximally close to development.
For our automation we use a framework which consist of MbUnit (Gallio as runner) and of MINT (addition to MbUnit, which is written by the customer we work with). MbUnit gives us Test Fixtures and Tests, and MINT adds additional smaller layer -- Actions inside tests. Example. Fixture is called 'FilteringFixture'. It consist of amount of tests like 'TestingFilteringById', or 'TestingFilteringWithSpecialChars', etc. Each test consist of actions, which are atomic unit of our test. Example of actions are - 'Open app (parameter)', 'OpenFilterDialog', etc.
We already have a lot of tests, which contain a lot of actions, it's a mess. They use internal API of the product we QA. Also, we start investigation a new Automation approach - UI automation via Microsoft UI Automation (sorry for tautology). So the necessity of some "exporter", or "reporter" tool became severe for managers.
Some time ago I have got a task to develop some application, which can parse a DLL (which contains all the fixtures, tests and actions), and export its structure in the human readable format (TXT, HTML, CSV, XML, any other). But, right after that, I went to vacation (2 weeks).
It happens so, that my girlfriend went to her family until vacation (she also got it), and I remained at home so alone. Thinking what me to do all this time (2 weeks), I remember about that "write exporter tool task" and how long I have been planning to start learning WPF. So, I decided to make my task during vacation, and also dress a application to WPF. At that time I heard something about MVVM, and I decided to implement it using pure MVVM.
DLL which can parse DLL with fixrtures etc had been written rather fast (~1-2 days). After that I had started with WPF, and this article will show you how it ended.
I have spent a major part of my vacation (almost 8 days!), trying to sorted it out in my head and code, and finally, it is done (almost). My girlfriend would not believe what I was doing all this time, but I have a proof!
Sharing my solution step by step in pseudo code, to help others avoid similar problems. This answer is more looks like tutorial =) (Really?). If you are interested what were the most complicated things while learning WPF from scratch, I would say -- make it all really MVVM and f*g TreeView binding!
If you want an archived file with solution, I can give it a bit later, just when I have made a decision, that it is worth of that. One limitation, I'm not sure I may share the MINT.dll, which brings Actions, as it has been developed by the customer of our company. But I can just remove it, and share the application, which can display information about Fixtures and Tests only, but not about actions.
Boastful words. With just a little C# / WinForms / HTML background and no practice I have been able to implement this version of the application in almost 1 week (and write this article). So, impossible is possible! Just take a vacation like me, and spend it to WPF learning!
Step by step tutorial (w/o attached files yet)
Short repetition of the task:
Some time ago I have got a task to develop an application, which can parse a DLL (which contains test fixtures, test methods and actions - units of our unit testing based automation framework), and export its structure in the human readable format (TXT, HTML, CSV, XML, any other). I decided to implement it using WPF and pure MVVM (both were absolutely new things for me). The 2 most difficult problems for me became MVVM approach itself, and then MVVM binding to TreeView control. I skip the part about MVVM division, it's a theme for separate article. The steps below are about binding to TreeView in MVVM way.
Not so important: Create DLL which can open DLL with unit tests and finds fixtures, test methods and actions (more smaller level of unit test, written in our company) using reflection. If you are interested in how it had been done, look here: Parsing function / method content using Reflection
DLL: Separated classes are created for both fixtures, tests and actions (data model, entity model?).We'll use them for binding. You should think by yourself, what will be an entity model for your tree. Main idea - each level of tree should be exposed by appropriate class, with those properties, which help you to represent the model in the tree (and, ideally, will take right place in your MVVM, as model or part of the model). In my case, I was interested in entity name, list of children and ordinal number. Ordinal number is a number, which represents order of an entity in the code inside DLL. It helps me show ordinal number in the TreeView, still not sure it's right approach, but it works!
public class MintFixutre : IMintEntity
{
private readonly string _name;
private readonly int _ordinalNumber;
private readonly List<MintTest> _tests = new List<MintTest>();
public MintFixutre(string fixtureName, int ordinalNumber)
{
_name = fixtureName;
if (ordinalNumber <= 0)
throw new ArgumentException("Ordinal number must begin from 1");
_ordinalNumber = ordinalNumber;
}
public List<MintTest> Tests
{
get { return _tests; }
}
public string Name { get { return _name; }}
public bool IsParent { get { return true; } }
public int OrdinalNumber { get { return _ordinalNumber; } }
}
public class MintTest : IMintEntity
{
private readonly string _name;
private readonly int _ordinalNumber;
private readonly List<MintAction> _actions = new List<MintAction>();
public MintTest(string testName, int ordinalNumber)
{
if (string.IsNullOrWhiteSpace(testName))
throw new ArgumentException("Test name cannot be null or space filled");
_name = testName;
if (ordinalNumber <= 0)
throw new ArgumentException("OrdinalNumber must begin from 1");
_ordinalNumber = ordinalNumber;
}
public List<MintAction> Actions
{
get { return _actions; }
}
public string Name { get { return _name; } }
public bool IsParent { get { return true; } }
public int OrdinalNumber { get { return _ordinalNumber; } }
}
public class MintAction : IMintEntity
{
private readonly string _name;
private readonly int _ordinalNumber;
public MintAction(string actionName, int ordinalNumber)
{
_name = actionName;
if (ordinalNumber <= 0)
throw new ArgumentException("Ordinal numbers must begins from 1");
_ordinalNumber = ordinalNumber;
}
public string Name { get { return _name; } }
public bool IsParent { get { return false; } }
public int OrdinalNumber { get { return _ordinalNumber; } }
}
BTW, I also created an interface below, which implement all the entities. Such interface can help you in the future. Still not sure, should I was also add there Childrens property of List<IMintEntity> type, or something like that?
public interface IMintEntity
{
string Name { get; }
bool IsParent { get; }
int OrdinalNumber { get; }
}
DLL - building data model: DLL has a method which opens DLL with unit tests and enumerating data. During enumeration, it builds a data model like below. Real method example is given, reflection core + Mono.Reflection.dll are used, don't be confused with complexity. All that you need - look how the method fills _fixtures list with entities.
private void ParseDllToEntityModel()
{
_fixutres = new List<MintFixutre>();
// enumerating Fixtures
int f = 1;
foreach (Type fixture in AssemblyTests.GetTypes().Where(t => t.GetCustomAttributes(typeof(TestFixtureAttribute), false).Length > 0))
{
var tempFixture = new MintFixutre(fixture.Name, f);
// enumerating Test Methods
int t = 1;
foreach (var testMethod in fixture.GetMethods().Where(m => m.GetCustomAttributes(typeof(TestAttribute), false).Length > 0))
{
// filtering Actions
var instructions = testMethod.GetInstructions().Where(
i => i.OpCode.Name.Equals("newobj") && ((ConstructorInfo)i.Operand).DeclaringType.IsSubclassOf(typeof(BaseAction))).ToList();
var tempTest = new MintTest(testMethod.Name, t);
// enumerating Actions
for ( int a = 1; a <= instructions.Count; a++ )
{
Instruction action = instructions[a-1];
string actionName = (action.Operand as ConstructorInfo).DeclaringType.Name;
var tempAction = new MintAction(actionName, a);
tempTest.Actions.Add(tempAction);
}
tempFixture.Tests.Add(tempTest);
t++;
}
_fixutres.Add(tempFixture);
f++;
}
}
DLL: Public property Fixtures of the List<MintFixutre> type is created to return just created data model ( List of Fixtures, which contain lists of tests, which contains lists of Actions ). This will be our binding source for TreeView.
public List<MintFixutre> Fixtures
{
get { return _fixtures; }
}
ViewModel of MainWindow (with TreeView inside): Contains object / class from DLL which can parse unit tests DLLs. Also exposes Fixtures public property from the DLL of List<MintFixutre> type. We will bind to it from XAML of MainWindow. Something like that (simplified):
var _exporter = MySuperDllReaderExporterClass ();
// public property of ViewModel for TreeView, which returns property from #4
public List<MintFixture> Fixtures { get { return _exporter.Fixtures; }}
// Initializing exporter class, ParseDllToEntityModel() is called inside getter
// (from step #3). Cool, we have entity model for binding.
_exporter.PathToDll = #"open file dialog can help";
// Notifying all those how are bound to the Fixtures property, there are work for them, TreeView, are u listening?
// will be faced later in this article, anticipating events
OnPropertyChanged("Fixtures");
XAML of MainWindow - Setup data templates: Inside a Grid, which contains TreeView, we create <Grid.Resources> section, which contains a set of templates for our TreeViewItems. HierarchicalDataTemplate (Fixtures and Tests) is used for those who have child items, and DataTemplate is used for "leaf" items (Actions). For each template, we specify which its Content (text, TreeViewItem image, etc.), ItemsSource (in case of this item has children, e.g. for Fixtures it is {Binding Path=Tests}), and ItemTemplate (again, only in case this item has children, here we set linkage between templates - FixtureTemplate uses TestTemplate for its children, TestTemplate uses ActionTemplate for its children, Action template does not use anything, it is a leaf!). IMPORTANT: Don't forget, that in order to "link" "one" template to "another", the "another" template must be defined in XAML above the "one"! (just enumerating my own blunders :) )
XAML - TreeView linkage: We setup TreeView with: linking with data model from ViewModel (remember public property?) and with just prepared templates, which represent content, appearance, data sources and nesting of tree items! One more important note. Don't define your ViewModel as "static" resource inside XAML, like <Window.Resources><MyViewModel x:Key="DontUseMeForThat" /></Window.Resources>. If you do so, then you won't be able to notify it on property changed. Why? Static resource is static resource, it initializes ones, and after that remains immutable. I might be wrong here, but it was one of my blunders. So for TreeView use ItemsSource="{Binding Fixtures}" instead of ItemsSource="{StaticResource myStaticViewModel}"
ViewModel - ViewModelBase - Property Changed: Almost all. Stop! When user opens an application, then initially TreeView is empty of course, as user hasn't opened any DLL yet! We must wait until user opens a DLL, and only then perform binding. It is done via OnPropertyChanged event. To make life easier, all my ViewModels are inherited from ViewModelBase, which right exposes this functionality to all my ViewModel.
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, args);
}
}
XAML - OnPropertyChanged and commanding. User clicks a button to opens DLL which contains unit tests data. As we using MVVM, then click is handled via commanding. At the end of the OpenDllExecuted handler OnPropertyChanged("Fixtures") is executed, notifying the Tree, that the property, to which it is bind to has been changed, and that now is time to refresh itself. RelayCommand helper class can be taken for example from there). BTW, as I know, there are some helper libraries and toolkits exist Something like that happens in the XAML:
And ViewModel - Commanding
private ICommand _openDllCommand;
//...
public ICommand OpenDllCommand
{
get { return _openDllCommand ?? (_openDllCommand = new RelayCommand(OpenDllExecuted, OpenDllCanExecute)); }
}
//...
// decides, when the <OpenDll> button is enabled or not
private bool OpenDllCanExecute(object obj)
{
return true; // always true for Open DLL button
}
//...
// in fact, handler
private void OpenDllExecuted(object obj)
{
var openDlg = new OpenFileDialog { ... };
_pathToDll = openDlg.FileName;
_exporter.PathToDll = _pathToDll;
// Notifying TreeView via binding that the property <Fixtures> has been changed,
// thereby forcing the tree to refresh itself
OnPropertyChanged("Fixtures");
}
Final UI (but not final for me, a lot of things should be done!). Extended WPF toolkit was used somewhere: http://wpftoolkit.codeplex.com/

Visual Studio: How to write Editor Extensions with WPF

Im trying to write a editor extension for Visual Studio. I have the downloaded VS SDK and created a new Visual Studio Package project. But the dummy control created for me is a Windows Forms control and not a WPF control. I'm trying to replace it with a WPF-control but not doing so well. Is this possible anyhow?
Another related question: Is it only possible to write text-editors? What I really want is a editor that looks more like a form with many different fields. But it doesn't seem to be what this is made for? There are a lot of interfaces on the EditorPane that imply a text-editor model only.
Ideally I want a editor much like the resx-editor where the file being edited has xml-content and the editor-ui is not a single textbox and where a generated cs-file is being outputted as a sub-file. Is this possible to do with editor extensions?
This is explained in detail here: WPF in Visual Studio 2010 – Part 4 : Direct Hosting of WPF content
So, if you use the standard Extensibility / Custom Editor sample that comes with the Visual Studio SDK, what you can do to test it is this:
1) Modify the provided EditorFactory.cs file like this:
// Create the Document (editor)
//EditorPane NewEditor = new EditorPane(editorPackage); // comment this line
WpfEditorPane NewEditor = new WpfEditorPane(); // add this line
2) create for example a WpfEditorPane.cs file like this:
[ComVisible(true)]
public class WpfEditorPane : WindowPane, IVsPersistDocData
{
private TextBox _text;
public WpfEditorPane()
: base(null)
{
_text = new TextBox(); // Note this is the standard WPF thingy, not the Winforms one
_text.Text = "hello world";
Content = _text; // use any FrameworkElement-based class here.
}
#region IVsPersistDocData Members
// NOTE: these need to be implemented properly! following is just a sample
public int Close()
{
return VSConstants.S_OK;
}
public int GetGuidEditorType(out Guid pClassID)
{
pClassID = Guid.Empty;
return VSConstants.S_OK;
}
public int IsDocDataDirty(out int pfDirty)
{
pfDirty = 0;
return VSConstants.S_OK;
}
public int IsDocDataReloadable(out int pfReloadable)
{
pfReloadable = 0;
return VSConstants.S_OK;
}
public int LoadDocData(string pszMkDocument)
{
return VSConstants.S_OK;
}
public int OnRegisterDocData(uint docCookie, IVsHierarchy pHierNew, uint itemidNew)
{
return VSConstants.S_OK;
}
public int ReloadDocData(uint grfFlags)
{
return VSConstants.S_OK;
}
public int RenameDocData(uint grfAttribs, IVsHierarchy pHierNew, uint itemidNew, string pszMkDocumentNew)
{
return VSConstants.S_OK;
}
public int SaveDocData(VSSAVEFLAGS dwSave, out string pbstrMkDocumentNew, out int pfSaveCanceled)
{
pbstrMkDocumentNew = null;
pfSaveCanceled = 0;
return VSConstants.S_OK;
}
public int SetUntitledDocPath(string pszDocDataPath)
{
return VSConstants.S_OK;
}
#endregion
}
Of course, you will have to implement all the editor logic (add interfaces, etc.) to mimic what's done in the Winforms sample, as what I provide here is really the minimal stuff for pure demonstration purposes.
NOTE: this whole "Content" thing only works starting with Visual Studio 2010 (so you need to make sure your project references Visual Studio 2010 assemblies, which should be the case if you start a project from scratch using Visual Studio 2010). Hosting WPF editors within Visual Studio 2008 is possible using System.Windows.Forms.Integration.ElementHost.
I'm not sure if the above is possible but a quick search did turn up this:
http://karlshifflett.wordpress.com/2010/03/21/visual-studio-2010-xaml-editor-intellisense-presenter-extension/
and this:
http://blogs.msdn.com/b/visualstudio/archive/2009/12/09/building-and-publishing-an-extension-for-visual-studio-2010.aspx
Failing that, could you not host a WPF control inside the winforms control using ElementHost? I know its a lame workaround but might allow you to develop in your favourite toolkit while you find a more permanent solution.
Best regards,
There is a sample VS Extension Package application source code on MSDN: Designer View Over XML Editor.
Description from site:
This Sample demonstrates how to create an extension with a WPF-based Visual Designer for editing XML files with a specific schema (XSD) in coordination with the Visual Studio XML Editor.
Admittedly solution is dedicated for VS2010 Extension Package, however it can be simply converted and attuned to VS2012 format - Target platform should be change to .NET 4.5, thereafter some references to VS2012 assemblies (v.11.0) should be added to build and run startup project:
Microsoft.VisualStudio.Shell.11.0.dll
Microsoft.VisualStudio.Shell.Immutable.11.0.dll
Microsoft.VisualStudio.Shell.Interop.11.0
In case of problems, please visit Q & A section of the site.

Can I implement my own view resolution service and have RequestNavigate use it?

I 'm fairly new to Prism and I 'm currently re-writing one of our existing applications using Prism as a proof of concept project.
The application uses MVVM with a ViewModel first approach: our ViewModel is resolved by the container, and an IViewResolver service figures out what view it should be wired up to (using name conventions amongst other things).
The code (to add a view to a tab control) at the moment looks something like this:
var vm = (get ViewModel from somewhere)
IRegion reg = _regionManager.Regions["MainRegion"];
var vw = _viewResolver.FromViewModel(vm); // Spins up a view and sets its DataContext
reg.Add(vw);
reg.Activate(vw);
This all works fine, however I 'd really like to use the Prism navigation framework to do all this stuff for me so that I can do something like this:
_regionManager.RequestNavigate(
"MainRegion",
new Uri("NameOfMyViewModel", UriKind.Relative)
);
and have Prism spin up the ViewModel + View, set up the DataContext and insert the view into the region.
I 've had some success by creating DataTemplates referencing the ViewModel types, e.g.:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Module01">
<DataTemplate DataType="{x:Type local:TestViewModel}">
<local:TestView />
</DataTemplate>
</ResourceDictionary>
...and have the module add the relevant resource dictionary into the applications resources when the module is initialized, but that seems a bit rubbish.
Is there a way to effectively take over view creation from Prism, so that when RequestNavigate is called I can look at the supplied Uri and spin up the view / viewmodel based on that? There’s an overload of RegionManager.RegisterViewWithRegion that takes a delegate that allows you to supply a view yourself, and I guess I’m after something like that.
I think I might need to supply my own IRegionBehaviorFactory, but am unsure what's involved (or even if I am on the right path!).
Any help appreciated!
--
note: Originally posted over at the prism codeplex site
Sure you can do that. I 've found that Prism v4 is really extensible, if only you know where to plug in.
In this case, you want your own custom implementation of IRegionNavigationContentLoader.
Here's how to set things up in your bootstrapper (the example is from a subclass of UnityBootstrapper from one of my own projects):
protected override void ConfigureContainer()
{
// IMPORTANT: Due to the inner workings of UnityBootstrapper, accessing
// ServiceLocator.Current here will throw an exception!
// If you want access to IServiceLocator, resolve it from the container directly.
base.ConfigureContainer();
// Set up our own content loader, passing it a reference to the service locator
// (it will need this to resolve ViewModels from the container automatically)
this.Container.RegisterInstance<IRegionNavigationContentLoader>(
new ViewModelContentLoader(this.Container.Resolve<IServiceLocator>()));
}
The ViewModelContentLoader itself derives from RegionNavigationContentLoader to reuse code, and will look something like this:
public class ViewModelContentLoader : RegionNavigationContentLoader
{
private readonly IServiceLocator serviceLocator;
public ViewModelContentLoader(IServiceLocator serviceLocator)
: base(serviceLocator)
{
this.serviceLocator = serviceLocator;
}
// THIS IS CALLED WHEN A NEW VIEW NEEDS TO BE CREATED
// TO SATISFY A NAVIGATION REQUEST
protected override object CreateNewRegionItem(string candidateTargetContract)
{
// candidateTargetContract is e.g. "NameOfMyViewModel"
// Just a suggestion, plug in your own resolution code as you see fit
var viewModelType = this.GetTypeFromName(candidateTargetContract);
var viewModel = this.serviceLocator.GetInstance(viewModelType);
// get ref to viewResolver somehow -- perhaps from the container?
var view = _viewResolver.FromViewModel(vm);
return view;
}
// THIS IS CALLED TO DETERMINE IF THERE IS ANY EXISTING VIEW
// THAT CAN SATISFY A NAVIGATION REQUEST
protected override IEnumerable<object>
GetCandidatesFromRegion(IRegion region, string candidateNavigationContract)
{
if (region == null) {
throw new ArgumentNullException("region");
}
// Just a suggestion, plug in your own resolution code as you see fit
var viewModelType = this.GetTypeFromName(candidateNavigationContract);
return region.Views.Where(v =>
ViewHasDataContract((FrameworkElement)v, viewModelType) ||
string.Equals(v.GetType().Name, candidateNavigationContract, StringComparison.Ordinal) ||
string.Equals(v.GetType().FullName, candidateNavigationContract, StringComparison.Ordinal));
}
// USED IN MY IMPLEMENTATION OF GetCandidatesFromRegion
private static bool
ViewHasDataContract(FrameworkElement view, Type viewModelType)
{
var dataContextType = view.DataContext.GetType();
return viewModelType.IsInterface
? dataContextType.Implements(viewModelType)
: dataContextType == viewModelType
|| dataContextType.GetAncestors().Any(t => t == viewModelType);
}
// USED TO MAP STRINGS OF VIEWMODEL TYPE NAMES TO ACTUAL TYPES
private Type GetTypeFromName(string typeName)
{
// here you need to map the string type to a Type object, e.g.
// "NameOfMyViewModel" => typeof(NameOfMyViewModel)
return typeof(NameOfMyViewModel); // hardcoded for simplicity
}
}
To stop some confusion about "ViewModel first approach":
You use more a "controller approach", but no "ViewModel first approach". A "ViewModel first approach" is, when you inject your View in your ViewModel, but you wire up both, your ViewModel and View, through a third party component (a controller), what by the way is the (I dont want to say "best", but) most loosely coupled approach.
But to answer your Question:
A possible solution is to write an Extension for the Prism RegionManager that does exactly what you have described above:
public static class RegionManagerExtensions
{
public static void AddToRegion<TViewModel>(
this IRegionManager regionManager, string region)
{
var viewModel = ServiceLocator.Current.GetInstance<TViewModel>();
FrameworkElement view;
// Get View depending on your conventions
if (view == null) throw new NullReferenceException("View not found.");
view.DataContext = viewModel;
regionManager.AddToRegion(region, view);
regionManager.Regions[region].Activate(view);
}
}
then you can call this method like this:
regionManager.AddToRegion<IMyViewModel>("MyRegion");

WPF DataTemplate/ControlTemplate and VS2008 designer

Suppose you have WPF Window composed of many elements that are using DataTemplates / ControlTemplates (ItemControls ... )
But you want to see how every DataTemplate looks like in VS Designer.
What more, if you define a ControlTemplate from as a Template located in another file to be able to view it with the content.
Something like MasterPage and ChildElements in ASP.NET
You can always see what elements have you put together.
Is this possible in WPF too?
Otherwise.. every change I make to the DataTemplate can be seen after a long-time-consuming compilation and start.
Thank you guys..
Stefan,
I think that you can do this by creating Design Time class as described in the link below:
http://karlshifflett.wordpress.com/2008/10/11/viewing-design-time-data-in-visual-studio-2008-cider-designer-in-wpf-and-silverlight-projects/
Hope this helps.
To do this extremely simply, just set a DataContext in your constructor:
public MyUserControl()
{
#if !RELEASE
//DataContext = new CustomerList { Customers = new [] {
// new Customer { Name = "Contoso", ZipCode = 12345 },
// new Customer { Name = "NorthWind", ZipCode = 12345 },
//}};
#endif
InitializeComponent();
...
}
Notice the fact that the code is commented out. When you want to see data, just uncomment the code. The #if !RELEASE protects you from accidentally including the sample data in your release (and from spending any CPU loading it).
If your sample data is big, just put it in XML or in a database and load it:
public MyUserControl()
{
#if !RELEASE
//DataContext = XmlSerializerManager.Deserialize<CustomerList>(
// File.ReadAllBytes("CustomerSampleData.xml"));
#endif
InitializeComponent();
...
}
In either case, the sample data will show up in the designer whenever you uncomment the code. When executing your application it will be replaced with the real data.

Resources