WPF Application using MVVM Toolkit will not compile with StartupEventHandler - wpf

I have a WPF application that does not compile when I attempt to add any event handler to the App class.
Below is all the code and the exception I am getting. The application uses the MVVM toolkit - so that may be a factor.
If someone could tell me what I may be missing or doing incorrectly, it would be greatly appreciated.
App.xaml code:
<Application x:Class="MyClient.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:Sample.ViewModel"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Startup="Application_Startup">
<Application.Resources>
<!--Global View Model Locator-->
<vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
<!-- Resources scoped at the Application level should be defined here. -->
<Style x:Key="TextBlockStyleFooter" TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="Margin" Value="1"/>
</Style>
<Style x:Key="TextBlockStyleClock" TargetType="TextBlock">
<Setter Property="FontFamily" Value="Arial"/>
<Setter Property="Foreground" Value="White"/>
<!--<Setter Property="Margin" Value="0, -1,"/>-->
<Setter Property="TextAlignment" Value="Center"/>
</Style>
<Style x:Key="BorderStyle1" TargetType="Border">
</Style>
</Application.Resources>
App.xaml.cs Code:
using System;
using System.Windows;
using System.Windows.Threading;
using GalaSoft.MvvmLight.Threading;
namespace Sample
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
static App()
{
DispatcherHelper.Initialize();
}
private void Application_Startup(object sender, StartupEventArgs e)
{
}
}
}
When I try to compile this, I get the following exception:
Error 1 'MyClient.App' does not contain a definition for 'Application_Startup' and no extension method 'Application_Startup' accepting a first argument of type 'EdgePokerClient.App' could be found (are you missing a using directive or an assembly reference?) C:\projects.git\MyClient\src\MyClient\App.xaml 7 73 MyClient

The issue here is that your XAML refers to MyClient.App whereas your code-behind file has the partial class in the Sample namespace. To the compiler, these are two separate classes. So the event handler you've defined in the one class (Sample.App) is not present in the generated class MyClient.App.
You just need to fix either the namespace in your code behind file or the x:Name attribute in the XAML file.
I'd also be careful with the static constructor on App. I'm not sure if the code generator will add a public parameterless constructor or not, but if it doesn't, having only a static constructor will effectively mean that App can't be instantiated.

I'd like to post this comment for other people getting this same error like i did.
I had this same error, however my x:class namespace wasn't different than the code behind namespace. Some tutorials says that after you put the Startup="Application_Startup" on your XAML, your code behind should be updated automatically. it didn't happen leading me to this error.
My Fix - Update code behind with
private void Application_Startup(object sender, StartupEventArgs e){}
before adding
Startup="Application_Startup"
to the xaml.
hope this come to be useful to somebody.

Related

Why I am getting "Type reference cannot find type" exception while referring ResourceDictionary in C# code

I am using following code to Create a Style in Resource Dictionary:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Chart="clr-namespace:TestApp.Controls.Chart">
<Style x:Key="DefaultLabelStyle" TargetType="{x:Type Chart:LabelStyle}">
<Setter Property="LabelBrush">
<Setter.Value>
<SolidColorBrush Color="Red"/>
</Setter.Value>
</Setter>
<Setter Property="LabelFontSize" Value="12.0"/>
<Setter Property="Visibility" Value="False"/>
<Setter Property="OrientationAngle" Value="0"/>
<Setter Property="LabelPlacement" Value="Top"/>
<Setter Property="LabelOrientation" Value="Normal"/>
</Style>
and then trying to consume it using following code:
public static void LoadSkin()
{
var _skinDictionary = new ResourceDictionary { Source = new Uri("/Chart;component/Resources/DefaultSkin.xaml", UriKind.RelativeOrAbsolute) };
}
but its throwing "Type reference cannot find type" exception, mentioning that unable to find LabelStyle. But LabelStyle is a public class in Chart.
What I am doing wrong here?
I tried checking other threads here with similar problem and tried to make those changes,
still it doesn't works :(
Please let me know your suggestions..!!
You cannot apply a Style to a type that is not derived from FrameworkElement or FrameworkContentElement. See the Remarks section in Style.TargetType.
Maybe your LabelStyle class could simply get its property values from resources like this:
<ResourceDictionary ...
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<sys:Double x:Key="LabelFontSize">12.0</sys:Double>
...
</ResourceDictionary>

Binding to SystemColors in Silverlight XAML

I have following code in WPF XAML and want it to be converted to Silverlight 4:
<Setter
Property="Background"
Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}" />
<Setter>
Unfortunately, Silverlight does not support x:Static.
Does anybody know how to port it properly without code behind, XAML-only?
Since you cannot access Static properties like that,you've to define your own "wrapper" class that will wrap the static properties, something like this:
public class StaticMemberAccess
{
public ResourceKey WindowBrushKey { return SystemColors.WindowBrushKey; }
//define other wrapper propeties here, to access static member of .Net or your classes
}
Then do this in XAML
<UserControl.Resources>
<local:StaticMemberAccess x:Key="SMA"/>
</UserControl.Resources>
<Setter
Property="Background"
Value="{Binding Source={StaticResource SMA}, Path=WindowBrushKey}" />
<Setter>
Hope, it gives you some idea. :-)
See this also:
Retrieving value from static extension XAML

Why doesn't my WPF style work?

Trying to put a style in app.xaml. My app.xaml reads:
<Application x:Class="TestApp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Application.Resources>
<Style x:Key="TestStyle" TargetType="Button">
<Setter Property="Background" Value="Red"/>
</Style>
</Application.Resources>
</Application>
My XAML for the button is as follows:
<Button Content="Click Me!" Style="{StaticResource TestStyle}" />
In the designer all looks OK but when I run the code it fails with:
Provide value on 'System.Windows.StaticResourceExtension' threw an exception.
I've stared at it for ages but can't spot the problem!
EDIT
It seems to be something to do with the application overall. If I copy my code into another fresh project it works fine. The only difference is that the window is loaded using the "StartupUri="MainWindow.xaml". In the one that doesn't work I load the window up during the App.Startup as follows:
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
new TestWindow().Show();
}
SOLUTION
Found the problem - I was missing an InitializeComponent call. Now the styles work in the final product but not in the designer. I'm going to ask a separate question about it.
Workaround: Just define a Name for the Application object:
< Application x:Name="App" ...
It worked for me!
Based on your edit: if you've got StartupUri="MainWindow.xaml" in the original xaml, but (as your code snippet suggests) you actually have a file called TestWindow.xaml, this could be the problem! Try changing it to StartupUri="TestWindow.xaml" in the original project....
You can make a try with {DynamicResource TestStyle}. Maybe TestStyle is not yet created when you apply it to the Button.
try this...
<Style x:Key="TestStyle" TargetType="{x:Type Button}">
<Setter Property="Background" Value="Red"/>
</Style>
usually, in WPF, you want your TargetType to be of the form {x:Type ...}
in silverlight, you would use TargetType="Button"

How do I alter the default style of a button without WPF reverting from Aero to Classic?

I've added PresentationFramework.Aero to my App.xaml merged dictionaries, as in...
<Application
x:Class="TestApp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary
Source="/PresentationFramework.Aero;component/themes/Aero.NormalColor.xaml" />
<ResourceDictionary
Source="pack://application:,,,/WPFToolkit;component/Themes/Aero.NormalColor.xaml" />
<ResourceDictionary
Source="/CommonLibraryWpf;component/ResourceDictionaries/ButtonResourceDictionary.xaml" />
<!-- Note, ButtonResourceDictionary.xaml is defined in an external class library-->
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
I'm trying to modify the default look of buttons just slightly. I put this style in my ButtonResourceDictionary:
<Style TargetType="Button">
<Setter Property="Padding" Value="3" />
<Setter Property="FontWeight" Value="Bold" />
</Style>
All buttons now have the correct padding and bold text, but they look "Classic", not "Aero". How do I fix this style so my buttons all look Aero but also have these minor changes? I would prefer not to have to set the Style property for every button.
Update
I should have mentioned this in the first place, but if I try to use BasedOn, as shown below, I get a StackOverflowException:
<Style BasedOn="{StaticResource {x:Type Button}}" TargetType="{x:Type Button}">
<Setter Property="Padding" Value="3" />
<Setter Property="FontWeight" Value="Bold" />
</Style>
This would normally work, but not with the Aero dictionaries merged in. If I comment those dictionaries out, the exception disappears.
Update 2
If I add an x:Key attribute and manually set the style, it works properly (Aero style with padding and bold), but as I said, I'd prefer that the style is automatically applied globally to all buttons.
Update 3
I just discovered a new wrinkle. In my app, ButtonResourceDictionary.xaml is placed in a class library (i.e., in an external project). If I move this file to a local folder, everything works fine. So, the problem seems to be a bad interaction caused by referencing various external resource dictionaries. I'm correcting my App.xaml code snippet (above) to reflect that ButtonResourceDictionary is actually defined externally.
I hope you've found a solution in the meantime. For everyone else, here is one workaround, and here is another. I am not sure whether this will help for your specific case though (especially the fact that you reference an embedded resource dictionary).
UPDATE
Here's a solution I came up with:
<Style TargetType="TextBox" BasedOn="{Common:StaticApplicationResource {x:Type TextBox}}">
<Setter Property="Height" Value="21"/>
</Style>
Where StaticApplicationResource is a custom MarkupExtension I wrote that simply calls TryFindResource:
[MarkupExtensionReturnType(typeof(object))]
public class StaticApplicationResource : MarkupExtension
{
public StaticApplicationResource(object pResourceKey)
{
mResourceKey = pResourceKey;
}
private object _ResourceKey;
[ConstructorArgument("pResourceKey")]
public object mResourceKey
{
get { return _ResourceKey; }
set { _ResourceKey = value; }
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (mResourceKey == null)
return null;
object o = Application.Current.TryFindResource(mResourceKey);
return o;
}
}
This way I don't have to reference my resource dictionaries outside of my App.xaml file , which is the way I like it :). You can also put more complicated logic in there too, allowing you to resolve the BasedOn style any way you like. Here is an excellent article showing you how to load resource dictionaries (and those that the framework resolves automatically) from code.
Based on your updates, you could do this (admittedly it is hideously ugly):
<Style x:Key="_buttonStyleBase"
BasedOn="{StaticResource {x:Type Button}}"
TargetType="{x:Type Button}">
<Setter Property="Padding" Value="3" />
<Setter Property="FontWeight" Value="Bold" />
</Style>
<Style TargetType="{x:Type Button}"
BasedOn="{StaticResource _buttonStyleBase}" />
Use the BasedOn attribute to inherit the properties from the Aero Style. This should solve your problem.
<Style
BasedOn="{StaticResource {x:Type Button}}"
TargetType="{x:Type Button}">
<Setter Property="Padding" Value="3" />
<Setter Property="FontWeight" Value="Bold" />
</Style>

Inheriting from Application Styles (WPF)

I am trying to inherit application-level styles for a certain Window in my WPF application, but I'm having trouble getting it to inherit rather than simply override the existing styles.
In App.xaml (under the App.Resources element) I define a style as such:
<Style TargetType="Button">
<Setter Property="Padding" Value="6"/>
<Setter Property="FontWeight" Value="Bold"/>
</Style>
And in the XAML fora a certain Window, I define the following under Window.Resources:
<Style TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Padding" Value="6"/>
<Setter Property="FontWeight" Value="Bold"/>
</Style>
The problem here is that the former (app) style is ignored as if the latter (window) style has overridden it. The BasedOn attribute is set, which is intended to indicate that existing styles should be inherited, as far as I know. Removing the attribute doesn't help either. The only potential cause of which I can think is that {StaticResource {x:Type Button}} only refers to the default WPF style and not the one I have define in App.xaml.
I am aware that this styling behaviour would be possible to accomplish using the x:Key attribute, but I was hoping for a more elegant way that allows me to apply styles with inheritance to all controls within a scope (i.e. application/window).
Update
Thanks for both of your replies. You are indeed right that things work as expected in a sample application. The difference is that I inadvertently failed to mention that the style in App.xaml is contained within a ResourceDictionary, as such:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="SettingsDictionary.xaml"/>
<ResourceDictionary>
<Style x:Key="DefaultButton" TargetType="Button">
<Setter Property="Padding" Value="4"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
Any suggestion on how to remedy matters in this case?
EDIT
After some research, I've found that the x:Key is being automatically generated if TargetType is set. So, the style in App.xaml is correct. However, the wpf designer is lacking some resource handling skills, and is not displayng both styles. If you build and run the project, both styles will be applied.
If your machine and VS2008 behave like the one upon which I tested your code.
Hope this helps.
EDIT 2
The resources and merged dictionaries in App.xaml have always been quirky.
I've solved the problem by moving the first style declaration out of the merged dictionary, like this:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<!--<ResourceDictionary Source="SettingsDictionary.xaml"/>-->
</ResourceDictionary.MergedDictionaries>
<Style TargetType="Button">
<Setter Property="Foreground" Value="Red"/>
<Setter Property="Padding" Value="4"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
</ResourceDictionary>
</Application.Resources>
Note also that giving the style an explicitly set key other than the {x:Type Button} will make it a non-default style and make it not apply automatically.
It is generally recommended to specify merged dictionaries only for resources from another file, and coded resources in the default space as above.
I'd second Jeff Wains comment in being surprised that your approach is not working as desired. In fact I'm unable to reproduce your issue via the following steps:
Created a new project via VS 2008 C# WPF application wizard.
resulting in App.xaml and Window1.xaml just like your example
Added a standard button from the toolbox to Window1.
Pasted your snippets as is, but modified one property each to observe the desired effect in the first place (having identical properties/values each is not what you intended to demonstrate I guess).
Well, this is just working fine, i.e. the button in Window1 inherits properties from both styles and modifying properties in either one does properly affect the button. Consequently their must be something weird going on behind the scenes in your project/environment? Have you tried a simple repro case like this already?

Resources