I have a XAML form for use in my application, and I have subclassed the Frame class to create my own, and edited the interface to specify my own class for the content (as I need to access properties on the content for data binding).
The problem comes then in the designer that the compiler says it cannot create an instance of my control - I've tried to do some designer checks on the offending property bit but that didnt work either.
How can I get the control to display? Works fine at runtime...
XAML:
<Grid Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2">
<views:PageFrame Name="Content_MainPage" Frame.NavigationUIVisibility="Hidden"/>
</Grid>
CS:
public new BaseView Content
{
get
{
if (DesignerProperties.GetIsInDesignMode(this))
{
return new BaseView();
}
else
{
return (BaseView)base.Content;
}
}
set
{
if (DesignerProperties.GetIsInDesignMode(this))
{
base.Content = new BaseView();
FrameTitle = "design mode";
}
else
{
base.Content = value;
FrameTitle = value.Title;
}
}
}
I came across a similar problem when creating my own Panel class.
Is your PageFrame class defined in the same assembly that your XAML lives in?
I found the only way I could get this to work was to move my "PageFrame" class into a new assembly. From memory I think I even had to build that assembly ahead of time, so that the assembly could be referenced via a file reference (as opposed to a project reference).
I hated this solution, so I hope you find a cleaner one :)
Have you got VS2008 SP1 installed? I had hoped MS would fix this bug. I haven't tried removing my workaround to check...
Its in the same assembly - and yes I have VS2008 SP1 installed too. Not that removing the above property lets it work fine from a vs point of view, but obviously not from my point of view!
I will give this a go - thanks Antony.
Related
I have really strange problem. I've created WPF project in 2012 or 2013 VS it doesn't matter. I use .NET 4.5.
I add a new Activity (Workflow class) to that project. Its name is CustomActivity.
Then I add a new class that has got an attached property, example below:
public class AttachedObject : DependencyObject
{
public static readonly DependencyProperty NameProperty = DependencyProperty.RegisterAttached(
"Name",
typeof(string),
typeof(AttachedObject),
new FrameworkPropertyMetadata(
string.Empty,frameworkPropertyMetadataOptions.AffectsRender));
public static void SetName(ContentControl element, string value)
{
element.SetValue(NameProperty, value);
}
public static string GetName(ContentControl element)
{
return (string)element.GetValue(NameProperty);
}
}
The last step is to change MainWindow class that way:
public MainWindow()
{
InitializeComponent();
var activity = new CustomActivity();
}
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wpfApplication1="clr-namespace:WpfApplication1;assembly=WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ContentControl wpfApplication1:AttachedObject.Name="MainArea"/>
</Grid>
</Window>
The problem is it doesn't compile because of below error:
Error 1 The type or namespace name 'CustomActivity' could not be found (are you missing a using directive or an assembly reference?) WpfApplication1\MainWindow.xaml.cs 13 32 WpfApplication1
CustomActivity has a default namespace. In obj folder there is CustomActivity.g.cs generated, so I have no idea what's going on.
It's 100% reproducible. When I remove using of CustomActivity or using of AttachedObject from xaml then the problem disappear.
Try replacing this:
xmlns:wpfApplication1="clr-namespace:WpfApplication1;assembly=WpfApplication1"
with this
xmlns:wpfApplication1="clr-namespace:WpfApplication1"
The error you're seeing is due to a "known" issue in WPF applications that xaml namespaces that reference clr namespace from current assembly your in don't require the full assembly qualified name. If you were to declare a xaml namespace that references a clr namespace from another assembly, than you would have to specify the full name (with the ;[assemblyname] syntax).
Workflow Foundation has nothing to do with it.
EDIT:
Didn't realize it was a xaml activity.
But still, you can make it work, maybe, with a few hacks, but I wouldn't recommend it.
The reason you get that error is due to the different code generation and build action VS uses when creating xaml artifacts for WPF (Page):
System.Windows.Application.LoadComponent(this, resourceLocater);
and when creating xaml activities (XamlAppDef):
typeof(CustomActivity).Assembly.GetManifestResourceStream(resourceName);
If you turn your CustomActivity xaml build action to Page, the whole thing will compile - but i'm guessing something else might be broken someplace else...or not, who knows. My guess is that these two kinds of xaml were not meant to live together in a VS WPF application project template. But you can still define activities in a WF activity library, that way your activities will also be more easily reusable for other projects, WPF, console or even services.
I have the same issue under Visual Studio 2017.
The problem in my case is that Visual Studio is not compiling the Workflow activities before the code that use them.
To fix it, what I did is to move all workflows to other project dll, so visual Studio is forced to compile the workflows before the classes that make use of them.
This may be a long shot, but I'm using ComponentOne's Spellchecker control for Silverlight. I made a test project, added a plain textbox and a button to it, added the references to the C1.Silverlight and C1.Silverlight.SpellChecker bits, and added the dictionary file to my project.
In the code, I called up the spellchecker on button1's click event and it worked SPLENDIDLY. The spellchecker dialog shows up, and works exactly as it should.
Since that test was successful, I then tried to implement this into my existing project. I've had no success for absolutely NO reason that I can determine, since I used the EXACT SAME code.
Here's the code I use to call the component:
using C1.Silverlight;
using C1.Silverlight.SpellChecker;
using C1.Silverlight.Resources;
public partial class MainPage : UserControl
{
C1SpellChecker spellChecker = new C1SpellChecker();
public MainPage()
{
InitializeComponent();
spellChecker.MainDictionary.LoadAsync("C1Spell_en-US.dct");
}
private void btnSpelling_Click(object sender, RoutedEventArgs e)
{
var dlg = new C1SpellDialog();
spellChecker.CheckControlAsync(txtArticle, false, dlg);
}
The references to C1.Silverlight and C1.Silverlight.Spellchecker are added to this project as well, and the dictionary as been added in the same fashion as well. The issue seems to be that for whatever reason the dictionary is not loading, because the spellChecker.Enabled method returns whether or not the main dictionary has been loaded. If I call MessageBox.Show("SpellChecker Enabled = " + spellChecker.Enabled.ToString()); it shows false, even though the call to load the dictionary is there (as you can see).
What would cause the dictionary to not load? Have I added it to my project incorrectly somehow?
EDIT: I suspect that I have added the dictionary to the project incorrectly, because the ComponentOne reference states:
If C1SpellChecker cannot find the
spelling dictionary, it will not throw
any exceptions. The Enabled property
will be set to false and the component
will not be able to spell-check any
text.
I just don't know what's wrong though because it was added in the same way that it was in the test project (Right clicked on the project.web->Add->Existing Item)
As always, thank you!
-Sootah
You could add the dictionary to the Silverlight app as an embedded resource and then load it using this code:
public MainPage()
{
InitializeComponent();
// load C1SpellChecker dictionary from embedded resource
var asm = this.GetType().Assembly;
foreach (var res in asm.GetManifestResourceNames())
{
if (res.EndsWith(".dct"))
{
using (var s = asm.GetManifestResourceStream(res))
{
sc.MainDictionary.Load(s);
break;
}
}
}
}
I think this post is duplicated in our forum as well, but will answer first here. Please try this:
1) Try to access the .dct file using your browser. If you cannot see it, it's probably because your web server is not serving that type of files. You need ton configure the web server to allow it.
2) verify the URL you are using is correct.http://helpcentral.componentone.com/CS/silverlight_161/f/78/p/86955/241328.aspx#241328
3) Check you are setting everything correctly: http://helpcentral.componentone.com/CS/silverlight_161/f/78/p/81924/227790.aspx#227790
Hope this helps!
When I modify my resource file (.resx) add text or modify, the constructor of my resource always go to internal and after that, when I run my silverlight I have an error in my binding XAML.
Is there a way to avoid this scenario? I need to go in the designer of my resource and put the constructor to public to solve the problem
I use my resource like this in my xaml file
<UserControl.Resources>
<resources:LibraryItemDetailsView x:Key="LibraryItemDetailsViewResources"></resources:LibraryItemDetailsView>
</UserControl.Resources>
<TextBlock FontSize="12" FontWeight="Bold" Text="{Binding Path=FileSelectedText3, Source={StaticResource LibraryItemDetailsViewResources}}"></TextBlock>
Another way to do this without code changes is as below. Worked well for me.
http://guysmithferrier.com/post/2010/09/PublicResourceCodeGenerator-now-works-with-Visual-Studio-2010.aspx
You can create a public class that exposes the resources through a property:
public class StringsWrapper
{
private static LibraryItemDetailsView _view = null;
public LibraryItemDetailsView View
{
get
{
if (_view == null)
{
_view = new LibraryItemDetailsView();
}
return _view;
}
}
}
Then in your XAML you can access your resource:
<UserControl.Resources>
<StringsWrapper x:Key="LibraryItemDetailsViewResources"></StringsWrapper>
</UserControl.Resources>
<TextBlock FontSize="12" FontWeight="Bold" Text="{Binding Path=View.FileSelectedText3, Source={StaticResource LibraryItemDetailsViewResources}}"></TextBlock>
This way the resx constructor can be internal!
Well, what I did was to add a command line utility to pre-build event of each Silverlight project that replaces each internal string with public :)
You can edit pre-build and post-build events by: Right-clicking on a project -> Properties -> Build Events.
I used a utility called RXFIND, it's free and can replace a string within selected files using a RegEx regular expression.
Here's the command line I'm using:
"$(SolutionDir)ThirdParty\rxfind\rxfind.exe" "$(ProjectDir)Resources\*.Designer.cs" "/P:internal " "/R:public " /Q /B:2
Please note, that all my resources are located under Resource directory within each project and the command line utility resides in \ThirdParty\rxfind directory
I also have the same error. To solve the problem I just created a public class that inherits from the class representing the resources file, knowing that it must also be public class this is my exep:
public class TrackResourceWrapper : TrackResource
{
}
with:
TrackResourceWrapper is inheriting class
TrackResource is the class which is located in the code resource file behind (public class)
Simply:
Add a new class that inherits from the resource class
In the App.xaml file, modify the resource class which you created
Done!
The reason for this is that you shouldn't be instantiating the class yourself. You should instead always use ConsoleApplication1.Resource1.ResourceManager which itself instantiates the class for you.
Here, ConsoleApplication1 is the name of your assembly and Resource1 the name of your resource file.
I created a macro to do this for me for each file I edit. I still have to remember to run it, but it's a lot quicker. Please see my post.
Does anyone know of some global state variable that is available so that I can check if the code is currently executing in design mode (e.g. in Blend or Visual Studio) or not?
It would look something like this:
//pseudo code:
if (Application.Current.ExecutingStatus == ExecutingStatus.DesignMode)
{
...
}
The reason I need this is: when my application is being shown in design mode in Expression Blend, I want the ViewModel to instead use a "Design Customer class" which has mock data in it that the designer can view in design mode.
However, when the application is actually executing, I of course want the ViewModel to use the real Customer class which returns real data.
Currently I solve this by having the designer, before he works on it, go into the ViewModel and change "ApplicationDevelopmentMode.Executing" to "ApplicationDevelopmentMode.Designing":
public CustomersViewModel()
{
_currentApplicationDevelopmentMode = ApplicationDevelopmentMode.Designing;
}
public ObservableCollection<Customer> GetAll
{
get
{
try
{
if (_currentApplicationDevelopmentMode == ApplicationDevelopmentMode.Developing)
{
return Customer.GetAll;
}
else
{
return CustomerDesign.GetAll;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
I believe you are looking for GetIsInDesignMode, which takes a DependencyObject.
Ie.
// 'this' is your UI element
DesignerProperties.GetIsInDesignMode(this);
Edit: When using Silverlight / WP7, you should use IsInDesignTool since GetIsInDesignMode can sometimes return false while in Visual Studio:
DesignerProperties.IsInDesignTool
Edit: And finally, in the interest of completeness, the equivalent in WinRT / Metro / Windows Store applications is DesignModeEnabled:
Windows.ApplicationModel.DesignMode.DesignModeEnabled
You can do something like this:
DesignerProperties.GetIsInDesignMode(new DependencyObject());
public static bool InDesignMode()
{
return !(Application.Current is App);
}
Works from anywhere. I use it to stop databound videos from playing in the designer.
There are other (maybe newer) ways of specifying design-time data in WPF, as mentioned in this related answer.
Essentially, you can specify design-time data using a design-time instance of your ViewModel:
d:DataContext="{d:DesignInstance Type=v:MySampleData, IsDesignTimeCreatable=True}"
or by specifying sample data in a XAML file:
d:DataContext="{d:DesignData Source=../DesignData/SamplePage.xaml}">
You have to set the SamplePage.xaml file properties to:
BuildAction: DesignData
Copy to Output Directory: Do not copy
Custom Tool: [DELETE ANYTHING HERE SO THE FIELD IS EMPTY]
I place these in my UserControl tag, like this:
<UserControl
...
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
...
d:DesignWidth="640" d:DesignHeight="480"
d:DataContext="...">
At run-time, all of the "d:" design-time tags disappear, so you'll only get your run-time data context, however you choose to set it.
Edit
You may also need these lines (I'm not certain, but they seem relevant):
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
When Visual Studio auto generated some code for me it used
if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
{
...
}
And if you extensively use Caliburn.Micro for your large WPF / Silverlight / WP8 / WinRT application you could use handy and universal caliburn's Execute.InDesignMode static property in your view-models as well (and it works in Blend as good as in Visual Studio):
using Caliburn.Micro;
// ...
/// <summary>
/// Default view-model's ctor without parameters.
/// </summary>
public SomeViewModel()
{
if(Execute.InDesignMode)
{
//Add fake data for design-time only here:
//SomeStringItems = new List<string>
//{
// "Item 1",
// "Item 2",
// "Item 3"
//};
}
}
Accepted answer didn't work for me (VS2019).
After inspecting what was going on, I came up with this:
public static bool IsRunningInVisualStudioDesigner
{
get
{
// Are we looking at this dialog in the Visual Studio Designer or Blend?
string appname = System.Reflection.Assembly.GetEntryAssembly().FullName;
return appname.Contains("XDesProc");
}
}
I've only tested this with Visual Studio 2013 and .NET 4.5 but it does the trick.
public static bool IsDesignerContext()
{
var maybeExpressionUseLayoutRounding =
Application.Current.Resources["ExpressionUseLayoutRounding"] as bool?;
return maybeExpressionUseLayoutRounding ?? false;
}
It's possible though that some setting in Visual Studio will change this value to false, if that ever happens we can result to just checking whether this resource name exist. It was null when I ran my code outside the designer.
The upside of this approach is that it does not require explicit knowledge of the specific App class and that it can be used globally throughout your code. Specifically to populate view models with dummy data.
I have an idea for you if your class doesn't need an empty constructor.
The idea is to create an empty constructor, then mark it with ObsoleteAttribute. The designer ignores the obsolete attribute, but the compiler will raise an error if you try to use it, so there's no risk of accidentaly using it yourself.
(pardon my visual basic)
Public Class SomeClass
<Obsolete("Constructor intended for design mode only", True)>
Public Sub New()
DesignMode = True
If DesignMode Then
Name = "Paula is Brillant"
End If
End Sub
Public Property DesignMode As Boolean
Public Property Name As String = "FileNotFound"
End Class
And the xaml:
<UserControl x:Class="TestDesignMode"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:vm="clr-namespace:AssemblyWithViewModels;assembly=AssemblyWithViewModels"
mc:Ignorable="d"
>
<UserControl.Resources>
<vm:SomeClass x:Key="myDataContext" />
</UserControl.Resources>
<StackPanel>
<TextBlock d:DataContext="{StaticResource myDataContext}" Text="{Binding DesignMode}" Margin="20"/>
<TextBlock d:DataContext="{StaticResource myDataContext}" Text="{Binding Name}" Margin="20"/>
</StackPanel>
</UserControl>
This won't work if you really need the empty constructor for something else.
I have a .NET 2.0 windows forms app, which makes heavy use of the ListView control.
I've subclassed the ListView class into a templated SortableListView<T> class, so it can be a bit smarter about how it displays things, and sort itself.
Unfortunately this seems to break the Visual Studio Forms Designer, in both VS2005 and 2008.
The program compiles and runs fine, but when I try view the owning form in the designer, I get these Errors:
Could not find type 'MyApp.Controls.SortableListView'. Please make sure that the assembly that contains this type is referenced. If this type is a part of your development project, make sure that the project has been successfully built.
There is no stack trace or error line information available for this error
The variable 'listViewImages' is either undeclared or was never assigned.
At MyApp.Main.Designer.cs Line:XYZ Column:1
Call stack:
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.Error(IDesignerSerializationManager manager, String exceptionText, String helpLink)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, String name, CodeExpression expression)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, String name, CodeExpression expression)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeStatement(IDesignerSerializationManager manager, CodeStatement statement)
The line of code in question is where it is actually added to the form, and is
this.imagesTab.Controls.Add( this.listViewImages );
listViewImages is declared as
private MyApp.Controls.SortableListView<Image> listViewImages;
and is instantiated in the InitializeComponent method as follows:
this.listViewImages = new MyApp.Controls.SortableListView<Image>();
As mentioned earlier, the program compiles and runs perfectly, and I've tried shifting the SortableListView class out to a seperate assembly so it can be compiled seperately, but this makes no difference.
I have no idea where to go from here. Any help would be appreciated!
It happened to me because of x86 / x64 architecture.
Since Visual Studio (the development tool itself) has no x64 version, it's not possible to load x64 control into GUI designer.
The best approach for this might be tuning GUI under x86, and compile it for x64 when necessary.
when you added the listview, did you add it to the toolbox and then add it to the form?
No, I just edited Main.Designer.cs and changed it from System.Windows.Forms.ListView to MyApp.Controls.SortableListView<Image>
Suspecting it might have been due to the generics led me to actually finding a solution.
For each class that I need to make a SortableListView for, I defined a 'stub class' like this
class ImagesListView : SortableListView<Image> { }
Then made the Main.Designer.cs file refer to these stub classes instead of the SortableListView.
It now works, hooray!
Thankfully I am able to do this because all my types are known up front, and I'm only using the SortableListView as a method of reducing duplicate code.
I had this problem too, related to merging massive SVN changes (with conflicts) in the *.Designer.cs file. The solution was to just open up the design view graphically, edit a control (move it to the left then right) and resave the design. The *.Designer.cs file magically changed, and the warning went away on the next compilation.
To be clear, you need to fix all of the code merge problems first. This is just a work around to force VS to reload them.
I've had a problem like this (tho not the same) in the past where my control was in a different namespace to my form even tho it was in the same project. To fix it I had to add a
using My.Other.Namespace;
to the top of the designer generated code file. The annoying thing was it kept getting blown away when the designer regenerated the page.
The assembly that contains MyApp.Controls.SortableListView isn't installed in the GAC by any chance is it?
when you added the listview, did you add it to the toolbox and then add it to the form?
Perhaps you forgot to add that:
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Release all resources used.
/// </summary>
/// <param name="disposing">true if managed resources should be removed otherwise; false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
// ...
this.components = new System.ComponentModel.Container(); // Not necessarily, if You do not use
// ...
}
I have had the same problem. After removing some of my own controls of the *.Designer.cs-File the problem was solved. After going back to the original code the problem still was solved. So it seems to be a problem with the Visual Sudio cache. At the moment I cannot reproduce this problem.
If you have the problem try to emtpy the folder
C:\Users\YOURNAME\AppData\Local\Microsoft\VisualStudio\VERSION\Designer\ShadowCache
Did it work?
I had something similar - a user control was referring to a remote serice (which I couldn't guarantee being available at design time).
This post on MSDN suggested that I add
if (this.DesignMode) return;
to the Load function of the control, or in my case to the point before the WCF client was initialised. That did the trick.
So
private readonly Client _client = new Client();
becomes
private Client _client;
public new void Load()
{
if(DesignMode) return;
_client = new Client();
}
I had the same issue. In my case this issue was due to resource initialization. I moved the following code from InitializeComponent method to ctor(After calling InitializeComponent). After that this issue was resolved:
this->resources = (gcnew System::ComponentModel::ComponentResourceManager(XXX::typeid));
In my case the problem was the folder's name of my project! Why I think this:
I use SVN and in the 'trunk\SGIMovel' works perfectly. But in a branch folder named as 'OS#125\SGIMovel' I can't open the designer for a form that uses a custom control and works in the trunk folder.
Just get off the # and works nice.