wpf c# can't open window - c#

I've created a new window in wpf named AfterLogin.
I'm trying to open it with button like
VMR_Launcher.AfterLogin af = new VMR_Launcher.AfterLogin();
af.Show();
and like that
AfterLogin af = new AfterLogin();
af.Show();
It throws error Cannot locate resource AfterLogin.xaml
I have other windows too, but they working with those commands, and this afterlogin not. idk why.
Every new window doesn't work too.

What I would do, which has solved these types of one off things for me in the past, is create a new window in the folder its going to be in and start to copy the code over. Try copying just some of the code and functionality and build up to all of the code. If you finish copying over forget about ever having a problem and dismiss it as a one off. Its hard for us programmers to give up on figuring out why a problem occurs, but sometimes its better to just solve it the easy way and move on.

Try doing this.
AfterLogin af = new AfterLogin();
af.ShowDialog();

Make sure that AfterLogin.xaml file is there in your project. If it is not then import it.
If it is already there, then there must be one App.xaml file inyour project.
Open it! Inside <Application> tag,there will be <Application.Resources> tag, inside this tag make sure that code similar following exists.
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="AfterLogin.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

Related

How to use resources in C# Visual Studio? [duplicate]

How do I create a resource that I can reference and use in various parts of my program easily?
My specific problem is that I have a NotifyIcon that I want to change the icon of depending on the state of the program. A common problem, but one I've been struggling with for a long time.
Well, after searching around and cobbling together various points from around StackOverflow (gee, I love this place already), most of the problems were already past this stage. I did manage to work out an answer to my problem though.
How to create a resource:
In my case, I want to create an icon. It's a similar process, no matter what type of data you want to add as a resource though.
Right click the project you want to add a resource to. Do this in the Solution Explorer. Select the "Properties" option from the list.
Click the "Resources" tab.
The first button along the top of the bar will let you select the type of resource you want to add. It should start on string. We want to add an icon, so click on it and select "Icons" from the list of options.
Next, move to the second button, "Add Resource". You can either add a new resource, or if you already have an icon already made, you can add that too. Follow the prompts for whichever option you choose.
At this point, you can double click the newly added resource to edit it. Note, resources also show up in the Solution Explorer, and double clicking there is just as effective.
How to use a resource:
Great, so we have our new resource and we're itching to have those lovely changing icons... How do we do that? Well, lucky us, C# makes this exceedingly easy.
There is a static class called Properties.Resources that gives you access to all your resources, so my code ended up being as simple as:
paused = !paused;
if (paused)
notifyIcon.Icon = Properties.Resources.RedIcon;
else
notifyIcon.Icon = Properties.Resources.GreenIcon;
Done! Finished! Everything is simple when you know how, isn't it?
The above didn't actually work for me as I had expected with Visual Studio 2010. It wouldn't let me access Properties.Resources, said it was inaccessible due to permission issues. I ultimately had to change the Persistence settings in the properties of the resource and then I found how to access it via the Resources.Designer.cs file, where it had an automatic getter that let me access the icon, via MyNamespace.Properties.Resources.NameFromAddingTheResource. That returns an object of type Icon, ready to just use.
The above method works well.
Another method (I am assuming web here) is to create your page. Add controls to the page. Then while in design mode go to: Tools > Generate Local Resource. A resource file will automatically appear in the solution with all the controls in the page mapped in the resource file.
To create resources for other languages, append the 4 character language to the end of the file name, before the extension (Account.aspx.en-US.resx, Account.aspx.es-ES.resx...etc).
To retrieve specific entries in the code-behind, simply call this method: GetLocalResourceObject([resource entry key/name]).
Code posted by Matthew Scharley has a memory leak:
paused = !paused;
if (paused)
notifyIcon.Icon = Properties.Resources.RedIcon;
else
notifyIcon.Icon = Properties.Resources.GreenIcon;
You should Dispose() notifyIcon.Icon before replacing it, because Properties.Resources.SOME_ICON creates a new Icon each time it is used.
This can be observed in the log, with this code:
Console.WriteLine(Properties.Resources.RedIcon.GetHashCode());
Console.WriteLine(Properties.Resources.RedIcon.GetHashCode());
Console.WriteLine(Properties.Resources.RedIcon.GetHashCode());
You will see 3 different Hash Codes in the log. This means these are different Objects.
So, the simple fix will be:
paused = !paused;
notifyIcon.Icon?.Dispose();
notifyIcon.Icon = paused
? Properties.Resources.RedIcon;
: Properties.Resources.GreenIcon;

WPF C# Application I get 2 main windows

I am really new to WPF and c#, and have some questions about how the applications are initialized. I am going through some tutorials on LINQ classes in the hopes that I can bind all of my SQL Server data with observableCollections.
One of the examples I found has a start like so (in the App.xaml.cs file):
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
MainWindow app = new MainWindow();
ProductViewModel context = new ProductViewModel();
app.DataContext = context;
app.Show();
}
}
When I run the application I get 2 main windows. The commands above execute and open the first one, but then a second one gets called from some system code which I can't see (I can see in dissasembler, but that does not really help). So it seems that the application that VS set up for me has a standard entry, but the sample code (from Rachel Lim) does not do this. I have searched for differences in various files (like App.g.i.cs which has the void Main() call) and both my application and the sample are the same. I am trying to "take control" of the application to handle creating my observablecollections with the LINQ classes. Is anyone familiar enough with VS and C# to give me some hints on what might be happening?
The problem is probably in your App.xaml which often has the following:
Application x:Class="WpfApplication1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>
If your App.xaml.cs opens a window in one of the events as you have demonstrated, then you need to make sure to remove that StartupUri="MainWindow.xaml" in your Application element.

NotImplementedException when overriding default phone resources

I'm am adding the following code to the constructor of App.xaml.cs in my WP7 application.
Resources["PhoneBackgroundBrush"] = new ImageBrush
{
ImageSource = new BitmapImage(new Uri("/images/bg.png", UriKind.Relative))
};
after running it I get NotImplementedException once the applicaion is opened.
Any idea of how can we do this?
What I'm trying to achieve is a single theme application like Facebook that always have white theme regardless of phone's theme.
As a note, getter on the resources always work, so it's not that accessing phone resources is totally blocked from code. (I'm using this to determine current theme and accent of phone).
var a = Resources["PhoneBackgroundBrush"]; // this works fine
For simple examples it isn't complicated when you know how, however you shouldn't rename PhoneBackgroundBrush, but create a new key for your resources.
You need to create the resources in App.xaml (or you can pull in MergedDictionaries other places too, but that's more advanced). Test.jpg needs to be a resource file in your project.
In App.xaml:
<Application.Resources>
<ImageBrush x:Key="MyImageBrush" ImageSource="Test.jpg"/>
</Application.Resources>
In a page for example:
Background="{StaticResource MyImageBrush}"
If you're starting to re-template a control (say a Button), that when you need to crack open Blend and modify the default styles of controls. It's pretty well documented, and builds on these same principles...
Basically the reason you're getting a NotImplementedException is because the setter for the Application.Resources is implemented like this:
set
{
throw new NotImplementedException();
}
The reason Facebook is all white, is because they defined their own colour resources, and used them everywhere. I've also made a always-white themed app. It just requires a little extra effort.

Strange Visual Studio Behaviour when setting Application Resource Dictionary

I'm trying to set the current WPF Application ResourceDictionary programatically. (I have a WindForms project, so no "App.xaml" to do that for me).
Note: If anyone knows how to bind the equivalent of an Application.Resources to a ElementHost and all of its child controls hierarchy, this is the ultimate objective here.
I added to my code:
Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri("/Middlewerks;component/Resources.xaml", UriKind.RelativeOrAbsolute) });
Now it works perfectly in the application, the styling is fine (i.e.: Grids' backgrounds are red. It's just a test style).
But if I open this form in the designer, Visual Studio goes crazy. The whole window uses my style!
Here's a screenshot: http://localhostr.com/files/8368cc/Failure.jpg
The cool part is that I found how to edit the Visual Studio 2010 ugly blue skin. The sad part is that won't make my customers happy when they develop with my control.
Feel free to try it and tell me how I should implement my resources without screwing everything up.
XAML Code: (shown in screenshot)
EDIT: Here is my temporary, very hackish solution so I can keep on developing. It really is a pain that "Application.Current" works on Visual Studio.
if (Application.Current.MainWindow == null || !Application.Current.MainWindow.Title.EndsWith(" - Microsoft Visual C# 2010 Express"))
{
Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri("/Middlewerks;component/Resources.xaml", UriKind.RelativeOrAbsolute) });
}
When I worked on a WinForms project that used WPF areas, I just used MergedDictionaries to bring in the resources I needed, whenever I needed them.
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="DefaultResourceDictionary.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
Can you get away with that? You can still put a code behind on the dictionary if you need to do more programmatically.
You can use this at any level on any element. That is, it doesn't have to be a Window as shown here.

Winforms App Not Displaying Graphical Elements in Design Mode

I wrote a bunch of code in the .cs file in c# for a winforms application. The application runs fine, and everything is in it's place.
Something like this:
using..
namespace Temp
{
public class Temp : Form
{
Button b1;
TextBox t1;
Temp()
{
b1.Text = "Some Text";
b1.Size = new Size(50,20);
...
}
void function1()
{
// stuff
}
static void Main()
{
Application.Run(new Temp());
}
}
}
How can I modify my code (or fix it somehow) so that the design view displays the elements in their correct positions and view so that I can visually edit them instead of having to trial/error everything.
Edit for Clarification
My application runs fine. The problem is, that I didn't use designer to create the application and so in the designer view, the app is empty. But not empty when I run it, since everything is positioned programmatically in the .cs file. My question is, how can I fix this, so that the designer shows the objects correctly.
There is no quick fix other than to redesign everything?
So to get this shown within the designer you have to know how the designer works.
For every MyForm.cs there will automatically be a file called MyForm.Designer.cs be created. Within this Designer file there will be only one function called InitializeComponents(). This function will be called within the constructor of your MyForm.cs file.
The design viewer itself is responsible for the Designer file, so any change to this file while the design view is open would normally be discarded. Also if you put some code into the designer file that is not needed be the designer will be truncated.
So the next question is, when will this truncation happen? When you freshly open the design viewer of a form, it will read in everything from the Designer.cs file without making any changes. If you make any changes onto the form by the designer the complete file will be rewritten with all the settings already read in including your latest changes.
This behaviour can be monitored if you open the designer file also as source code view, make some little changes in design mode and afterwards take a close look at the left of the source file. There will be the changes marked with a yellow or a green marker.
Now after all this stuff of informations, you can try the following procedure to get your code into the designer:
Open the design view and put some simple control onto your form (e.g. TextBox)
Save and close the design view and open the Designer.cs file as source file
Copy all your variables name of your controls at the end of the file, right below the textBox1 line
Copy all your control property settings within the InitializeComponent() function right below the property settings of the TextBox
Copy all your control constructors to the top of the file, right below the constructor of the TextBox
Save the file and open your form in design view
Select the dummy TextBox on the design view and delete it
This change within the DesignView leads to a complete rewrite of the designer.cs file, ordering all your manually added stuff the right way.
So this is the way to go. Last but not least another little trick:
Every programmer uses the using-statement to not write the whole path to every class (like System.Windows.Forms.TextBox), but the designer writes always the whole path. To make it a little easier for your copy and paste session you can also add a using statement at the top of the file. After saving and changing something in Design View all this stuff will be re-written automatically. So you don't need to add all this paths manually while your adding your stuff to the Designer.cs file.
Your best option is probably to use the properties panel in the designer to set the positions etc (or maybe just drag them?).
You could go digging around in the designer file for the form (something.Designer.cs), but this isn't a fantastic idea because it can be pretty sensitive to changing things in ways the designer doesn't expect. Having said that, it looks like you're not actually using the designer to make your form (the class would be partial, for one thing), in which case you're SOL.
In that case, you need to copy the designer code from CS to designer.cs. So that you can use designer. I think this is the simplest approach.
Looks like this file was hacked from a class file instead of being generated by the system when you create a new winform.
You need at least an InitializeComponent(); call in your constructor. However you are missing a lot of other code that is generated for you when you create the file such as Dispose().
Best bet would be to right click your project in the solution explorer and click Add Windows Form then start over.

Categories