wpf visual studio designer won't load user controls - wpf

The view below is a container for three user controls, and I started getting this error after refactoring application resources:
Error 295 Could not create an instance of type 'FilterPanel'. C:...\ProjectPickerWindow.xaml
Here is the xaml for the view:
<Window x:Class="Smack.ConstructionAdmin.WpfPresentation.Views.ProjectPicker.ProjectPickerWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local ="clr-namespace:Smack.ConstructionAdmin.WpfPresentation.Views.ProjectPicker"
xmlns:res="clr-namespace:Smack.ConstructionAdmin.WpfPresentation"
Background="{DynamicResource {x:Static res:SmackResources.WaveWindowBackground}}"
Title="{Binding Path=DisplayName}" FontFamily="Arial" FontSize="12"
SizeToContent="WidthAndHeight" MinWidth="300"
>
<DockPanel LastChildFill="True">
<local:FilterPanel DockPanel.Dock="Top" DataContext="{Binding}" Padding="3" />
<local:StatusAndButtons DockPanel.Dock="Bottom" DataContext="{Binding}" Margin="3, 7" />
<local:Listing DataContext="{Binding}" Margin="3, 0"/>
</DockPanel>
The app runs fine, and I can undo the refactorings, but I would prefer not to. All of the user controls display fine in their designer windows.
Can someone tell me how to get this to display in the designer?
Cheers,
Berryl
=== ADD'L INFO # Andrew ===
Great general checklist, if not the fix yet.
1) no silent binding errors
2) the designer works great after commenting out the FilterPanel!
3) no noticeable behavior change; all tests past too
4) yeah, I may have not left enough bread crumbs to nail the exact refactor but major ones were:
-- put all converters for the presentation in the own ResourceDic
-- had the FilterPanel reference generic.xaml, which has all mergedResourceDics. It referenced a specific Dic called ListingStyles.xaml, which used to have the converters
As an aside, do any tools help find Resource 'problems' (Snoop, Mole?)? Is there anything like FxCop to find bad practices??

Not yet an answer but some suggestions as there is not enough information to go on without knowing more about the app: (Posted as an answer as I thought it too long for a comment).
These designer only issues are a pain to track down as the root cause is often not specifically related to where the error arises.
This looks as if FilterPanel has a dependency on an object that doesn't yet exist. I have usually found these to be either due to not resolving resource dictionaries correctly or ValueConverter parameters not cast properly to types or initialised at Design time.
Things to try - in ascending order of speed
1) Run the app and look at the Output window to ensure there are no silent binding errors.
2) Narrow down the issue - if you comment out the line that refers to the FilterPanel does the designer work? Often the error crops up in the next line.
3) Although the app appears to run OK has this introduced different behaviours?
4) Step back through your refactorings to find the point at which the problem arose.
I have found Expression Blend to be more tolerant but not necessarily more verbose when it does fall over.
UPDATE:
If you haven't already you may need to add the ThemeInfo custom attribute to your custom controls so they can find their resources - although I think if this mechanism were not working the app would throw an Exception. Anyhow the declaration is
[assembly:ThemeInfo(
//Theme specific resources,
//Generic resources
)]

There is a bunch of valid code/xaml that the VS2K8 designer cannot handle. A lot of them the Blend designer can handle.
If your control needs to be constructed in a special way before it can be 'used', then VS will blow up.
One VS2008 problem is controls from an abstract class. here or here which sounds like what may have happened if you are "refactoring"

Related

Is there any free Visual Studio plug-in/extension or external program to visualize XAML DataTemplate?

Visual Studio (10) gives the expected message "Intentionally Left Blank" in the designer.
I know already that I can do this with Blend, just looking around if there is an alternative solution...
I don’t really mind to graphically edit the template; I want only to see it without having to run the application.
Thanks!
Not exactly what you might want, but you can use XamlPad and just paste the content of your datatemplate into it. As long as you don't have layout related bindings, it should work well. Bindings are just ignored by xamlpad, and you need to add the 2 wpf namespace aliases by hand.
for example:
<TextBlock xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Text="{Binding test}"
Background="Red"
Width="20" Height="20"/>
the textblock is empty in XamlPad, but everything else works as expected.

Static verification of bindings

Or "how do you make sure all your bindings stay correct?"
(this is kinda lengthy, but bear with me, I tried to make it as short as I could)
Consider the following example:
<TextBox Name="tb" />
<TextBlock Text="{Binding Text.TheProp, ElementName=tb}" />
It is perfectly known at compile time that the binding is incorrect (i.e. the parser knows the type of element tb, and therefore, it knows the type of it's Text property, and therefore, it knows that TheProp doesn't exist).
Yet, this code will compile and run (although with a binding error message in debug output).
This behavior may come in very handy in some situations: no matter what exact type my data is, as long as it has appropriately named properties, I'm ok. Thus, we get sort of "declarative duck typing".
However, duck typing is not always a good thing.
Specifically, while using the MVVM pattern, I know (most of the time) the exact types of all my ViewModel objects. On the other hand, the models become more and more complex over time, which gets me worried about future refactoring: what if I decide to rename some properties, or, God forbid, put them in a separate aggregated object? What's going to happen with all my bindings then? Will I have to rake all XAML files by hand? And even without refactoring - what if I simply make a typo?
A similar problem is already solved in other places of XAML. If, for instance, you put an incorrect property name in Style/Setter/#Property, you get a compile time error.
TemplateBinding also provides such verification. Which is very handy.
So, ideally, I would love to see something like this:
ProductViewModel.cs:
public class ProductViewModel
{
public Name { get; set; }
public Price { get; set; }
}
ProductView.XAML:
<UserControl x:Class="Shopping.View.ProductView"
x:DataContextType="vm:ProductViewModel"
xmlns:vm="clr-namespace:Shopping.ViewModel"
... >
<TextBox Text="{Binding Name}" /> <!-- OK -->
<TextBox Text="{Binding Price}" /> <!-- OK -->
<TextBox Text="{Binding ABC}" /> <!-- Compile time error: there is no property ABC in ProductViewModel -->
</UserControl>
ShoppingCart.XAML:
<UserControl x:Class="Shopping.View.ShoppingCartView"
x:DataContextType="vm:ShoppingCartViewModel"
xmlns:vm="clr-namespace:Shopping.ViewModel"
... >
<ItemsControl ItemsSource="{Binding Products}"
ItemType="vm:ProductViewModel" > <!-- Static check happens here
ShoppingCartViewModel.Products must
implement IEnumerable<ProductViewModel> -->
<ItemsControl.ItemTemplate>
<DataTemplate DataType="vm:ProductViewModel">
<view:ProductView /> <!-- DataContext is known to be of correct type
because of DataTemplate.DataType property -->
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</UserControl>
But let's get back to reality. In reality, all that dreaming is just not going to happen in the near future.
However, I am sure I'm not the first person to have this problem.
So, finally, the question is: How do you make sure your bindings are correct? And that they stay that way?
How about static analysis of your Xaml performed as a post-build step?
As part of .Net 4, Microsoft released a new System.Xaml library to provide robust Xaml parsing and serialization support independent of WPF. They are now beginning to build all kinds of interesting things on top of it, some of which may help you out.
In the XamlToolkit, for example, you'll find the XamlDOM that enables you to do easy static analysis of Xaml files. And taking that a bit further, there's FxCop rules for XAML.
Of most interest is Rob Relyea's BindingFinder that has the explicit goal of type checking Bindings in Xaml. This requires that you have type hints in your Xaml, like the DataType attribute in a DataTemplate, or the the new d:DataContext attribute on your Views (which Blend uses to provide design-time data). It then uses the XamlDOM to check that everything matches up.
Update: Resharper 6 now provides intellisense for data bindings, and warnings if you get your property paths wrong.
As a practical matter, I've never found this to be a problem, at least when using the MVVM pattern. The view model only exists in support of the view. I'm not going to change one without changing the other. Refactoring the view model isn't going to break the bindings in the view because it makes no sense to refactor the view model for its own sake. You'll only refactor the view model when (and because) you're changing the design of the view.
The other reason that I don't have this problem is that I'm not developing the view model independently of Expression Blend. For all but the most trivial UIs, I build my view models using some kind of dependency injection so that I can create a test data source that's usable in Expression Blend. When I create bindings in Blend, I know right away whether or not I've done it right.
As with MVVM in general, doing this is an unbelieveable pain in the ass until you understand what you're doing and why. (This long blog post by Jonas Follesø gives a pretty good overview of how to use Ninject for this purpose, though there are no end of other frameworks you can use.) I'm sure that there are problems that I haven't uncovered yet with this methodology - above and beyond the problem that I've added DI frameworks and Expression Blend onto the heap of things that I need to understand to develop WPF applications.
Pablo Casals said that constant experimentation keeps the artist young. I don't feel young.

PropertyValueEditor and DependencyObject in Blend 3 - Silverlight DesignTime support

I'm working on a set of controls that has a number of DependencyProperties. The properties are themselves DependencyObjects and created during the get method of the properties. During the Get method, they are also set back to the propertybag using the SetValue() method, so they are in fact valid in Xaml and their properties can be storyboarded without having to explicitly created in the the visual tree.
These DependencyObjects has all its properties as DependencyProperties as well, for supporting DataBinding. They are as mentioned above possible to use in Storyboards.
At the same time I'm developing special designtime support for Blend 3 for these properties and have created an InlineEditorTemplate in the form of a Control. I create the template and set it for the PropertyValueEditor like this:
var vectorEditControl = new FrameworkElementFactory(typeof (VectorEditorControl));
var dataTemplate = new DataTemplate {VisualTree = vectorEditControl};
InlineEditorTemplate = dataTemplate;
In the Control I have the following:
<Grid DataContext="{Binding Value}">
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding Path=X, Mode=TwoWay}"/>
<TextBox Text="{Binding Path=Y, Mode=TwoWay}"/>
<TextBox Text="{Binding Path=Z, Mode=TwoWay}"/>
</StackPanel>
</Grid>
The editor shows up and I can edit the data. And even while debugging, I see that it actually sets the data back to the DependencyProperties on the DependencyObjects, but nothing happens to the Xaml. So the data is actually not persisted in any way in the Xaml and lost when I close the Xaml file and open it again.
Is there anything I need to do specifically for it to actually get into the Xaml? I was under the impression that this would happen automatically?
Excellent Question!
The core issue you're running into a misunderstanding as to what PropertyEditors in Blend/Cider end up databinding to.
Consider this object graph:
- MyControl
-- MyControl.MyProperty
--- FooClass
---- FooClass.BarProperty
Let's look at a scenario where we have a PropertyEditor (of any type: Inline, Dialog or Extended) to property MyControl.MyProperty.
When inside MyPropertyPropertyEditor you'd expect to get a fully settable copy of FooClass and be able to manipulate it's members.
That's a good assumption, but the wrong one.
The core issue is that Blend/Cider have elaborate data structures that represent your model at design time. There's about 3-5 levels of abstraction in how Blend/Cider interact with an actual control.
Creating those levels of abstraction allows Expression Blend / Visual Studio designers to be leveraged between framewroks (Silverlight / WPF) and support advanced scenarios (like Property transactions and property chaining).
So, the value you actually get to DataBind to is just one of those levels of abstraction.
Don't believe me? In your custom PropertyEditor, register for this.DataContextChanged event and checkout the type in this.DataContext. You'll end up getting the PropertyValue class (or one of it's friends).
Every single property change you want persisted to XAML (and shown on the design surface) should go through those abstraction layers.
the question you have to ask yourself is "Where do I get one of these absteaction classes for my PropertyValue.Value property instance?".
Well, what I'd do if I were you is create a ModelItem around MyControl.MyProperty and set that as your PropertyEditor.DataContext.
We've shipped an example of using ModelFactory.CreateItem in the Silverlight Toolkit as part of the Chart DefaultInitializer: Source Code, Ning Zhang (Awesome Design Time Dev) explains about ModelItem
If you've got follow-up questions I'd consider pinging PeteBl or UnniR through the Silverlight Insiders mailing list.
Sincerely,
-- Justin
It partly solves my problem. I'm having a dialog with UnniR for a followup.
I couldn't see how I could use this together with the PropertyValueEditor, but for default values this is brilliant and something I'll implement ASAP.
Thanks.

Making a DataTemplate blendable

How can I make a Datatemplate for a ViewModel blendable (designable in expression blend). When I go to resources and try to edit the DataTemplate directly all I see on the Drawingborad is a blank rectangle. This is because the DataTemplate is not bound to anything. Of course I can create a UserControl and create some designtime data in code there to see the template but I now would have to switch back and forth between the resource (to edit) and the usercontrol (to see the result of my edit). Isn't there a more direct way to edit and see my DataTemplate?
It's a bit of a stretch to use, but Blend has a feature called "Design-Time Data" that can help you out. It's tough to get started at first, but once you do a few it's pretty easy. It kind of forces you into a nice pattern for DataContext as well.
Here's a good link on the subject: http://www.robfe.com/2009/08/design-time-data-in-expression-blend-3/
Here's a few choice excerpts:
On Design-Time Sizes
...design time properties can be
safely ignored by other tools and they
are ignored at the runtime
(mc:Ignorable specifies that the
namespace with the "d" prefix can be
ignored).
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Expression Blend uses two design time
properties (d:DesignWidth,
d:DesignHeight) to specify a size for
a control to be used at design time...
On Design-Time Data Sources
I stumbled across d:Datacontext when I
was playing with Blend 3 and tried
adding a “live datasource” to my
window. I thought it was going to
behave just like the old way of
setting a DataContext, but when I ran
my application, there was no data! ...
So the upshot is, now we can write
code like this:
...
<Grid ...
DataContext="{StaticResource GameDataSource}"
d:DataContext="{StaticResource DesignTime_DateDataSource}">
Note that this is for Blend 3 if you want first-party support for these features. They are pretty good - there's even a designer for the design-time data, though I've not looked into those features yet.
Applying To DataTemplates
This is something I sorta made up, but it seems to work. Here I'm using the Design-Time data feature to pull data into the visual element's d:DataContext. You'd have to do this for every top-level element that needed a DataContext set.
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<!-- Resource dictionary entries should be defined here. -->
<DataTemplate x:Key="MyTemplate">
<TextBlock Text="{Binding Text}" d:DataContext="{StaticResource SampleDataSource}" />
</DataTemplate>
</ResourceDictionary>
The binding syntax is a little bit more explicit if you are using a DataTemplate with a DataType set, but it still works:
<DataTemplate DataType="{x:Type vm:MyViewModel}" >
<TextBlock Text="{Binding Text}"
d:DataContext="{Binding Source={StaticResource SampleDataSource}}" />
</DataTemplate>
This strategy will allow you to see how the DataTemplate will work while editing it directly, however you won't be able to see the result on any view that utilizes that DataTemplate unless you actually run the app. This is a limitation of Blend at the moment due to the fact that they don't appear to be using Mocks, but rather complete replacement objects. If blend ever adds the ability to create a new fake data source by clicking on "New DataSource -> Based on Referenced Object -> MyCustomerObject", then you will be in business.
It's possible you could overcome this limitation with some attached property trickery of your own, but it would be difficult at best.
Alternative
An alternative that will work in every situation, but is a bit more cumbersome to setup is setting up StaticResources that swap out fake data for real data during runtime, but in the designer show static sample data.
Here's a really great article by Karl Shifflett that includes some of these techniques and a few videos on it:
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,
Anderson
This strategy will allow you to see
how the DataTemplate will work while
editing it directly, however you won't
be able to see the result on any view
that utilizes that DataTemplate unless
you actually run the app. This is a
limitation of Blend at the moment due
to the fact that they don't appear to
be using Mocks, but rather complete
replacement objects. If blend ever
adds the ability to create a new fake
data source by clicking on "New
DataSource -> Based on Referenced
Object -> MyCustomerObject", then you
will be in business.
If I want to use acutal ViewModel mocks I guess it is the best way to create actual ViewModel instances and the references them with d:DataContext (e.g. using a ObjectDataProvider or x:Static)

What to do when WPF Window doesn't recognize user control defined in the same project?

I have a window "Operation" in XAML that uses a user control "Status" defined in the same project. When I build the solution, it returns ok, but when I open the design view for the Window, visual studio says "Could not create an instance of type 'Status'. The XAML for the Window "Operation" is below:
<Window x:Class="TCI.Indexer.UI.Operacao"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:tci="clr-namespace:TCI.Indexer.UI.Controles"
Title=" "
MinHeight="550"
MinWidth="675"
Loaded="Load"
ResizeMode="NoResize"
WindowStyle="None"
WindowStartupLocation="CenterScreen"
WindowState="Maximized"
Focusable="True">
<Canvas Name="canv">
<tci:Status x:Name="ucStatus"/>
<Grid Canvas.Top="0" Canvas.Left="0">
<StackPanel Orientation="Horizontal">
<!-- Indices -->
<Label Width="200"/>
</StackPanel>
</Grid>
</Canvas>
</Window>
The xmlns:tci is the namespace where the Status Usercontrol is. And tci:Status becomes underlined in blue when this error happens. How to use a UserControl like this?
I was consistently having this problem with one control in my project and wound up resolving it by changing all of my images to DynamicResource rather than StaticResource.
The really strange thing is that the designer worked just fine for the control itself and showed the images as expected. It was only when I used the control inside my main window that the designer gave me the "Could not create instance of " message.
I don't know exactly whats the solution, but that happens to me too from time to time. I end up deleting declaration of the namespace, rebuilding and trying again. :\
Try cleaning your entire project, then do a full rebuild. The WPF designer in VS is poorly done, in my opinion, and there are weird issues like this all over the place.
I recommend not relying on Design View for anything, at this point - it's just too unstable. Try Expression Blend, it's a little bit better with things like this. If you don't want to go that route, you're probably better off building and running your app :-(
If you're running VS 2008, do you have SP1 installed?
I typically see this when I haven't built the control. Make sure you build the control and see if you still see the problem. Occasionally, VS just gets confused and you need to close and open the control you are having a problem with. In this case, that would be your window.
Similar to what Jon Norton said, I also found this link (-link removed, see below-) that implicates resources. I had the situation described in the link, and Jon's fix sorted it.
EDIT
Sorry, the link now requires a login and the page doesn't exist anymore. I couldn't find what it was supposed to be after three years.

Resources