While designing a new WPF application I noticed exceptions not being thrown during data binding for controls with DataTemplates. To test I wrote the following simple user control with as little logic as possible. I'm using .NET 3.5 SP1, VS2008 SP1 running on WIN7.
When the DataContext is set, TestMethod is called and an exception is thrown in the codebehind but the application doesn't break.
Would someone mind explaining what is happening when the DataTemplate is being created? Specifically I'm interested in where the exception goes.
Below is the XAML code:
<UserControl x:Class="WPF2008.DataTemplateQuestion"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<UserControl.Resources>
<DataTemplate x:Key="TESTKey">
<Border BorderBrush="Black" BorderThickness="10">
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<TextBox Grid.Row="0" Text="{Binding Path=Txt}" />
<TextBox Grid.Row="1" Text="{Binding Path=Lbl}" />
<TextBox Grid.Row="2" Text="Am I disabled?" />
<TextBox Grid.Row="3" Text="I am disabled." IsEnabled="False" />
</Grid>
</Border>
</DataTemplate>
</UserControl.Resources>
<Grid>
<Label x:Name="lblTest" Content="{Binding Path=TestMethod}" ContentTemplate="{StaticResource TESTKey}" />
</Grid>
</UserControl>
Below is the codebehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WPF2008
{
public partial class DataTemplateQuestion : UserControl
{
public DataTemplateQuestion()
{
try
{
InitializeComponent();
lblTest.DataContext = new TestClass();
}
catch (Exception e)
{
// ADDING A BREAKPOINT HERE DOESN'T CATCH THE EXCEPTION
throw e;
}
}
}
public class TestClass
{
public TestValue TestMethod
{
get
{
// BREAKPOINT WILL BE HIT WHEN DEBUGGING BUT THE EXCEPTION DISAPPEARS
throw new Exception("WATCH ME DISAPPEAR");
return new TestValue { Lbl = "Label", Txt = "Text" };
}
}
public class TestValue
{
public string Lbl { get; set; }
public string Txt { get; set; }
}
}
}
Exceptions thrown by data bindings get translated into trace, which are delivered to the DataBindingSource TraceSource, which has a source name of "System.Windows.Data".
You can convert these into exceptions by creating a subclass of TraceListner that throws an exception on a trace, and add it to the Listeners collection of the TraceSourceSource. This can be done either in code or in your App.config file.
Here is how you would do it in code:
System.Diagnostics.PresentationTraceSources.DataBindingSource.Listeners.Add(
new MyTraceListener());
See TraceSource and TraceListener documentation and samples for more details.
Exceptions get eaten by data bindings, and result in the data binding being disabled (I'm not 100% sure this is the case here, I'm too lazy to put it into VS).
Another possibility is that you may be hitting http://support.microsoft.com/kb/976038 if you are running a 64-bit OS.
Related
Very new to WPF, followed along some youtube tutorials utilizing MVVM and Caliburn Micro, and had the ActiveItem working properly so I am sure my set up is sound. Since completing that tutorial I have tried to customize my app and my intended feature with ActiveItem does not work. App launches with no errors and my login successfully retrieves information from the database and logs me in and displays my name in the bottom left corner.
Here is the intended function:
I have my ShellView as the login page, and after the user signs in it triggers the active item to be the space behind the login rectangle. This code triggers but the login stays visible. It triggers WelcomeViewModel which is just a rectangle with a blue background. The border login doesn't actually disappear, it should just get covered up by the active window (at least for now).
Clicking the space brings up the ContentControl so I am pretty sure it is high-z order, but something is still not right. If I double click the space, it selects the ContentControl and shows its background color appearing on top of the log in which is desired, but not what I see when the application runs.
Xaml for ShellView:
<Window x:Class="ProductivityTool.Views.ShellView"
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"
xmlns:local="clr-namespace:ProductivityTool.Views"
xmlns:model="clr-namespace:ProductivityTool.ViewModels"
mc:Ignorable="d"
d:DataContext="{x:Type model:ShellViewModel}"
Title="Productivity Tool" Height="900" Width="1200" MinWidth="900" MinHeight="700">
<Grid Background="Transparent" RenderTransformOrigin="0.487,0.497">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200" />
<ColumnDefinition Width="auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="100" />
<RowDefinition Height="*" />
<RowDefinition Height="60" />
</Grid.RowDefinitions>
<!--Row 1-->
<!--
<TextBlock Text="{Binding Path=FullName, Mode=OneWay}" Grid.Row="1" Grid.Column="0"></TextBlock>
-->
<!--Oneway only pulls from the property, but never overwrote the property because it is one way-->
<!--Row 2-->
<!--
<TextBox MinWidth="100" Grid.Row="2" Grid.Column="0" x:Name="FirstName" HorizontalAlignment="Left"></TextBox>
<TextBox MinWidth="100" Grid.Row="2" Grid.Column="0" x:Name="LastName" HorizontalAlignment="Right"></TextBox>
-->
<!--Row 3-->
<!--OnewaytoSource only overwrites the property, opposite of OneWay-->
<!--
<ComboBox Grid.Row="3" Grid.Column="0" x:Name="People"
SelectedItem="{Binding Path=SelectedPerson, Mode=OneWayToSource}"
DisplayMemberPath="FirstName"
HorizontalAlignment="Left" Width="100"/>
<TextBlock Grid.Column="0" Grid.Row="3" x:Name="SelectedPerson_LastName" HorizontalAlignment="Right"/>
-->
<!--Row 4-->
<!--
<Button x:Name="ClearText" Grid.Row="4" Grid.Column="0">Clear Text</Button>
-->
<!--Row 5-->
<StackPanel x:Name="StackPanel" Orientation="Vertical" Grid.Column="0" Grid.Row="1" Background="Blue">
<Button x:Name="Phonebook" HorizontalAlignment="Center" Width="auto" Margin="10" Click="Phonebook_Click">Phonebook</Button>
<Button x:Name="LoadPageTwo" HorizontalAlignment="Center" Width="auto">RCPS</Button>
</StackPanel>
<!--content control is the main window of the ShellView, different pages are just different active items-->
<Border Margin="272,208,-401,255" Padding="5" BorderThickness="1" Background="Gray" CornerRadius="20" Grid.Column="1" Grid.Row="1">
</Border>
<TextBox x:Name="textBoxEmail" Grid.Column="1" HorizontalAlignment="Left" Height="30" Margin="498,246,-347,433" Grid.Row="1" VerticalAlignment="Center" Width="191"/>
<TextBox x:Name="textBoxUID" Grid.Column="1" HorizontalAlignment="Left" Height="30" Margin="498,327,-346,352" Grid.Row="1" VerticalAlignment="Center" Width="191"/>
<TextBlock FontSize="15" Margin="344,245,-143,433" Text="Employee Number:" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Center" Padding="3" Height="31"/>
<TextBlock FontSize="15" Margin="363,327,-125,352" Text="Email:" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Center" Padding="3" Height="30" />
<Button x:Name="Loginbtn" Grid.Column="1" Margin="321,391,-347,278" Grid.Row="1" Content="LOGIN" Click="LoginBtn_Click">
</Button>
<Label x:Name="lblSignedInAs" HorizontalContentAlignment="Center" Margin="10,26,0,0" Grid.Row="2" VerticalAlignment="Top" Height="26" Width="181"/>
<Label x:Name="lblLogged" Content="Logged Out" HorizontalContentAlignment="Center" Margin="10,0" Grid.Row="2" VerticalAlignment="Top" Width="181"/>
<ContentControl Grid.Row="1" Grid.Column="1"
x:Name="ActiveItem" Margin="0,0,-647,0"
Background="Blue"/>
</Grid>
</Window>
Code for ShellViewModel:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Caliburn.Micro;
using ProductivityTool.Models;
using ProductivityTool.Views;
namespace ProductivityTool.ViewModels
{
public class ShellViewModel : Conductor<object>
{
//private string _lblLogged;
//private string lblLoggedInAs;
private string _firstName = "Tim"; // Don't change this
private string _lastName;
private BindableCollection<PersonModel> _people = new BindableCollection<PersonModel>();
private PersonModel _selectedPerson;
public ShellViewModel() //Constructor
{
People.Add(new PersonModel { FirstName = "Tim", LastName = "Corey" });
People.Add(new PersonModel { FirstName = "Bill", LastName = "Jones" });
People.Add(new PersonModel { FirstName = "Sam", LastName = "Yet" });
}
public string FirstName
{
get { return _firstName; }
set
{
_firstName = value;
NotifyOfPropertyChange(() => FirstName);
NotifyOfPropertyChange(() => FullName); //Whenever a value of first name is changed, update fullname
}
}
public string LastName
{
get { return _lastName; }
set
{
_lastName = value;
NotifyOfPropertyChange(() => LastName);
NotifyOfPropertyChange(() => FullName); //Whenever a value of last name is changed, update fullname
}
}
public String FullName
{
get { return $"{ FirstName } { LastName }"; }
}
public BindableCollection<PersonModel> People
{
get { return _people; }
set { _people = value; }
}
public PersonModel SelectedPerson
{
get { return _selectedPerson; }
set
{
_selectedPerson = value;
NotifyOfPropertyChange(() => SelectedPerson);
}
}
//Return true or true for yes we can clear the text
public bool CanClearText(string firstName, string lastName)
{
//return !String.IsNullOrWhiteSpace(firstName) || !String.IsNullOrWhiteSpace(lastName);
if (String.IsNullOrWhiteSpace(firstName) && String.IsNullOrWhiteSpace(lastName))
{
return false;
}
else
{
return true;
}
}
//Perameters should start with lowercase, properties should start with uppercase
public void ClearText(string firstName, string lastName)
{
FirstName = "";
LastName = "";
}
public void LoadWelcomePage()
{
ActivateItem(new WelcomeViewModel());
}
public void LoadPageTwo()
{
//ActivateItem(new RegistrationViewModel());
}
}
}
Code-behind for ShellView (database info removed for privacy):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using ProductivityTool.ViewModels;
namespace ProductivityTool.Views
{
/// <summary>
/// Interaction logic for ShellView.xaml
/// </summary>
public partial class ShellView : Window
{
private ShellViewModel _viewModel; //this is needed to access methods from the view model, format _viewModel.method();
public ShellView()
{
InitializeComponent();
_viewModel = new ShellViewModel();
this.DataContext = _viewModel;
}
private void LoginBtn_Click(object sender, RoutedEventArgs e)
{
string loginCredentials;
if (string.IsNullOrWhiteSpace(textBoxEmail.Text))
{
loginCredentials = textBoxUID.Text;
}
else
{
loginCredentials = textBoxEmail.Text;
}
if (string.IsNullOrEmpty(loginCredentials))
{
MessageBox.Show("No credentials entered.");
}
else
{
string email = loginCredentials;
SqlConnection con = new SqlConnection("Data Source=source;Database=database;Trusted_Connection=Yes;");
con.Open();
SqlCommand cmd = new SqlCommand("Select * from UProfile where Email='" + email + "'", con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
DataSet dataSet = new DataSet();
adapter.Fill(dataSet);
if (dataSet.Tables[0].Rows.Count > 0)
{
string username = dataSet.Tables[0].Rows[0]["UserName"].ToString();
}
else
{
MessageBox.Show("Error");
}
lblLogged.Content = "Signed in as:";
lblSignedInAs.Content = dataSet.Tables[0].Rows[0]["UserName"].ToString(); //Display who is signed in currently
con.Close();
_viewModel.LoadWelcomePage();
}
}
private void Phonebook_Click(object sender, RoutedEventArgs e)
{
_viewModel.LoadWelcomePage();
}
}
}
Here is the WelcomeViewModel class that I want to call:
using Caliburn.Micro;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProductivityTool.Models;
namespace ProductivityTool.ViewModels
{
public class WelcomeViewModel : Screen
{
}
}
This is identical to the FirstChildViewModel that the tutorial was based on that was working at one point. Here is that:
using Caliburn.Micro;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProductivityTool.ViewModels
{
public class FirstChildViewModel : Screen
{
}
}
Apologies for messy code, I want to include everything so you guys have the full picture. Most of it is legacy from the tutorials I did that I keep for reference. If there is a better way to achieve this effect, please let me know.
I stepped through the code and verified that LoadWelcomePage is triggering. I also tried setting this method to be triggered from the button on the menu to the left and it didn't change anything. I messed with the order of ContentControl in the xaml thinking it's a z-index thing, but that didn't work. Actually assigning Z-index values also didn't work. I removed the login border and all of its children from the screen and just tried to have the ContentControl appear upfront but the Z-index looks proper it doesn't work correctly. I also tried different window and grid backgrounds, like transparent, thinking it was hidden behind either the grid or the window but it always remains hidden. I also tried setting the d:DataContext as recommended by another post but it didn't change anything.
While doing the tutorials, I had the same buttons and views being triggered and it was working, but now that my use-case is slightly different things have broken. I'm mostly convinced it is a z-index issue, but it's a simple layout and things seem to be as they should so I am stuck. Thanks in advance for the help.
After more testing, I find out that my _viewModel.LoadWelcomePage is triggering, but not actually doing anything. Assigning the methods that activateitem to different buttons and clicking those makes everything work fine. Because this is more of a c# question, I will close this question and open another one if I can't figure out how to get my method trigger to work.
I want to display dummy data in the design window of a WPF GridView and found a similar example: Answer: Design time data for datatemplate in xaml - Stack Overflow
I created a new WPF App (.NET Framework 4.6.1) named WpfDataTemplate and copied in the code snippets from the example into MainWindow.xaml.cs and MainWindow.xaml. All additions are noted in comments with ##.
Unexpected Behavior:
The line <local:MyMockClass x:Key="DesignViewModel" /> produces the error "Object reference not set to an instance of an object."
The test text # strings are not displayed in the Designer.
The test text # strings are not displayed in the Window at runtime.
Questions:
What is the cause of the error?
What do I need to change for the code to work as expected?
MainWindow.xaml
<Window x:Class="WpfDataTemplate.MainWindow"
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"
xmlns:local="clr-namespace:WpfDataTemplate"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<!-- ## BEGIN ADD -->
<Window.Resources>
<local:MyMockClass x:Key="DesignViewModel" />
</Window.Resources>
<!-- ## END ADD -->
<Grid>
<!-- ## BEGIN ADD -->
<ListBox x:Name="standardLayoutListBox"
d:DataContext="{Binding Source={StaticResource DesignViewModel}}"
ItemsSource="{Binding MyListBoxItems}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Label Grid.Column="0" Content="{Binding text1}" />
<Label Grid.Column="1" Content="{Binding text2}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<!-- ## END ADD -->
</Grid>
MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
// ## BEGIN ADD
using System.Collections.ObjectModel;
// ## END ADD
namespace WpfDataTemplate
{
// ## BEGIN ADD
public class MyMockClass
{
public MyMockClass()
{
MyListBoxItems.Add(new MyDataClass() { text1 = "test text 1", text2 = "test text 2" });
MyListBoxItems.Add(new MyDataClass() { text1 = "test text 3", text2 = "test text 4" });
}
public ObservableCollection<MyDataClass> MyListBoxItems { get; set; }
}
public class MyDataClass
{
public string text1 { get; set; }
public string text2 { get; set; }
}
// ## END ADD
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
Firstly you need to initialise your collection in your MyMockClass.
public class MyMockClass
{
public MyMockClass()
{
MyListBoxItems = new ObservableCollection<MyDataClass>()
MyListBoxItems.Add(new MyDataClass() { text1 = "test text 1", text2 = "test text 2" });
MyListBoxItems.Add(new MyDataClass() { text1 = "test text 3", text2 = "test text 4" });
}
public ObservableCollection<MyDataClass> MyListBoxItems { get; set; }
}
I use the design instance in my Window like so:
d:DataContext="{d:DesignInstance Type=local:MyMockClass, IsDesignTimeCreatable=True}"
I am trying to write a simple Silverlight application that has a few button on it but I keep receiving this error. I have gone file explorer to see about changing the permissions of the file so that MS Studio can find it but so far have found nothing to change.
Question: Is there something that has to be change in Visual Studio for Silverlight to work?
Silverlight 4 is what my target will be for the WEBApplication.
I am not really certain what needs to be added to this question to make it so that everyone will know what I am asking. I think that it is just a file from MS that has to be enabled and that was the SilverlightApplication3.dll but I am having no real luck enabling it.
Error:
Error 1 Could not load the assembly file:///C:\Users\itpr13266\Desktop\C++\SilverlightApplication3\SilverlightApplication3\obj\Debug\SilverlightApplication3.dll. This assembly may have been downloaded from the Web. If an assembly has been downloaded from the Web, it is flagged by Windows as being a Web file, even if it resides on the local computer. This may prevent it from being used in your project. You can change this designation by changing the file properties. Only unblock assemblies that you trust. See http://go.microsoft.com/fwlink/?LinkId=179545 for more information.
XML:
<UserControl x:Class="SilverlightApplication3.MainPage"
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"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="28,64,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="28,93,0,0" Name="button2" VerticalAlignment="Top" Width="75" />
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="28,122,0,0" Name="button3" VerticalAlignment="Top" Width="75" />
<Image Height="124" HorizontalAlignment="Left" Margin="31,156,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="332" />
<Border BorderBrush="Silver" BorderThickness="1" Height="120" HorizontalAlignment="Left" Margin="113,24,0,0" Name="border1" VerticalAlignment="Top" Width="251">
<TextBox Height="102" Name="textBox1" Width="221" />
</Border>
</Grid>
</UserControl>
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace SilverlightApplication3
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
}
}
Code:
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace SilverlightApplication3
{
public partial class App : Application
{
public App()
{
this.Startup += this.Application_Startup;
this.Exit += this.Application_Exit;
this.UnhandledException += this.Application_UnhandledException;
InitializeComponent();
}
private void Application_Startup(object sender, StartupEventArgs e)
{
this.RootVisual = new MainPage();
}
private void Application_Exit(object sender, EventArgs e)
{
}
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
// If the app is running outside of the debugger then report the exception using
// the browser's exception mechanism. On IE this will display it a yellow alert
// icon in the status bar and Firefox will display a script error.
if (!System.Diagnostics.Debugger.IsAttached)
{
// NOTE: This will allow the application to continue running after an exception has been thrown
// but not handled.
// For production applications this error handling should be replaced with something that will
// report the error to the website and stop the application.
e.Handled = true;
Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
}
}
private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
{
try
{
string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", #"\n");
System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
}
catch (Exception)
{
}
}
I have created very small WPF application and facing one problem. I have below classes.
Employee.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StaticResourceVsDynamicResource
{
public class Employee
{
public string strName;
public int nId;
public Employee()
{
strName = "Default name";
nId = -1;
}
public string Name
{
get{return strName;}set{strName = value;}
}
public int ID
{
get{return nId;}set{nId = value;}
}
}
}
MainWindow.xamal.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace StaticResourceVsDynamicResource
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
this.Resources["objEmployee"] = new Employee { Name = "Changed employee", ID = 100};
this.Resources.Add("myBrush",new SolidColorBrush(SystemColors.GrayTextColor));
}
}
}
MainWindow.xamal
<Window x:Class="StaticResourceVsDynamicResource.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:StaticResourceVsDynamicResource"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<x:ArrayExtension Type="{x:Type sys:String}" x:Key="objNames">
<sys:String>A1</sys:String>
<sys:String>A2</sys:String>
</x:ArrayExtension>
<local:Employee x:Key="objEmployee"></local:Employee>
</Window.Resources>
<Grid>
<Grid Height="100" HorizontalAlignment="Left" Margin="281,12,0,0" Name="grid3" VerticalAlignment="Top" Width="200" >
<ComboBox ItemsSource="{StaticResource ResourceKey=objNames}" Height="23" HorizontalAlignment="Left" Margin="48,37,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" />
</Grid>
</Grid>
Above xaml code is intresting. When I build this code I didn't get any error. For whatever reason I just shuffle position of <x:ArrayExtension> and <local:Employee> and I start getting below error.
The name 'InitializeComponent' does not exist in the current context
When I am declaring <local:Employee> before <x:ArrayExtenion> then only I am getting this error. I am sure this has to do something with namespace, but I am not able to figure it out. See the below code which is causing compilation error.
<Window.Resources>
<local:Employee x:Key="objEmployee"></local:Employee>
<x:ArrayExtension Type="{x:Type sys:String}" x:Key="objNames">
<sys:String>A1</sys:String>
<sys:String>A2</sys:String>
</x:ArrayExtension>
</Window.Resources>
Can anyone help? Seems to be a strange problem but it is...
Regards,
Hemant
I've had the same problem. The way I resolved it was by changing the build action of the XAML file to Page.
To credit the source where I found the solution:
http://blog.mahop.net/post/Compile-Error-for-WPF-Files-The-name-InitializeComponent-does-not-exist-in-the-current-context.aspx
I have a problem updating the WPF Designer when binding to custom dependency properties.
In the following example, I create a simple Ellipse that I would like to fill with my custom MyAwesomeFill property. The MyAwesomeFill has a default value of a Yellow SolidColor brush.
The problem is that in the control form of the designer I cannot see the default fill of the ellipse (Yellow), instead the ellipse is filled with SolidColor (#00000000). However, when I run the application everything works PERFECTLY.
Do you have any ideas why this may be happenning?
Thanks.
Here's the code that I use:
XAML:
<UserControl x:Class="TestApplication.MyEllipse"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<Grid>
<Ellipse Stroke="Black" StrokeThickness="5" Fill="{Binding MyAwesomeFill}"></Ellipse>
</Grid>
</UserControl>
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace TestApplication
{
public partial class MyEllipse : UserControl
{
#region Dependency property MyAwesomeFill
//Define and register dependency property
public static readonly DependencyProperty MyAwesomeFillProperty = DependencyProperty.Register(
"MyAwesomeFill",
typeof(Brush),
typeof(MyEllipse),
new PropertyMetadata(new SolidColorBrush(Colors.Yellow), new PropertyChangedCallback(OnMyAwesomeFillChanged))
);
//property wrapper
public Brush MyAwesomeFill
{
get { return (Brush)GetValue(MyAwesomeFillProperty); }
set { SetValue(MyAwesomeFillProperty, value); }
}
//callback
private static void OnMyAwesomeFillChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
MyEllipse m = (MyEllipse)obj;
m.OnMyAwesomeFillChanged(e);
}
#endregion
//callback
protected virtual void OnMyAwesomeFillChanged(DependencyPropertyChangedEventArgs e)
{
}
public MyEllipse()
{
InitializeComponent();
DataContext = this;
}
}
}
Code behind is not guaranteed to be run by the designer. If you add your MyEllipse control to a window it will run (ellipse in window has yellow background) but not when you look at the control directly. This means it will work for users of your control which is what is important.
To fix it to look good when opening up MyEllipse in the designer, add a fallback value.
<Ellipse
Stroke="Black"
StrokeThickness="5"
Fill="{Binding MyAwesomeFill, FallbackValue=Yellow}">
</Ellipse>