Search Results

Search found 918 results on 37 pages for 'usercontrol'.

Page 14/37 | < Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >

  • WPF ResourceDictionary and DynamicResource

    - by lanicor
    i am new to WPF so maybe this will be "noob" question but i can't find answer to it (and it seems so easy)... well i am programing WPF app and i want to use smth similar to css for webpages, so i found ResourceDictionary and tried to use it... I have main window in which i create Frame and on click some UserControl is loaded to that same Frame.I include my ResourceDictionary (root/style/Styles.xaml) to my main window like this: <Window.Resources> <ResourceDictionary x:Key="styles" Source="style/Styles.xaml" /> </Window.Resources> in which i have: <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Style x:Key="ProductsRequired" TargetType="{x:Type Label}"> <Setter Property="Height" Value="28" /> ... I don't use it on my main window but want to use it on my UserControls, which are loaded to that main window and i try to use it like this: <Label Name="product1" Style="{DynamicResource ProductsRequired}" /> Warning i am getting all the time is: The resource "ProductsRequired" could not be resolved. I even tried including Styles to my UserControl <UserControl.Resources> <ResourceDictionary x:Key="styles" Source="../style/Styles.xaml" /> </UserControl.Resources> and nothing happens... Well my question is long but i wanted to be clear... :) P.S. all that logic works in C# code btw private ResourceDictionary myStyles = new ResourceDictionary(); Style ProductsRequired = myStyles["ProductsRequired"] as Style; product1.Style = ProductsRequired;

    Read the article

  • Call any webservice from the same $.ajax() call

    - by Andreas
    Hi! Im creating a usercontrol which is controled client side, it has an javascript-file attatched to it. This control has a button and upon click a popup appears, this popup shows a list of my domain entities. My entities are fetched using a call to a webservice. Im trying to get this popup usercontrol to work on all my entities, therefore i have the need to call any webservice needed (one per entity for example) with the same $.ajax() call. I have hiddenfields for the webservice url in my usercontrol which you specify in the markup via a property. So far so good. The problem arise when i need some additional parameters to the webservice (other than pagesize and pageindex). Say for example that one webservice takes an additional parameter "Date". At the moment i have my parameters set up like this: var params = JSON.stringify({ pageSize: _this.pageSize, pageIndex: _this.pageIndex }); and then i call the webservice like so: $.ajax({ webserviceUrl, params, function(result) { //some logic }); }); What i want to do is to be able to add my extra parameters (Date) to "Param" when needed, the specification of these parameters will be done via properties of the usercontrol. So, bottom line, i have a set of default parameters and want to dynamically add optional extra parameters. How is this possible? Thanks in advance.

    Read the article

  • Problem Binding to a Brush Property in WPF

    - by Krisc
    Working in WPF, writing a custom user control. I am trying to change the background property of the Border element when I change the value of a property of the class. Right now I am working on simply binding it to a DP, though if there is a better way I am open to suggestions. Here is the XAML for the UserControl <UserControl x:Class="MyProject.MyControl" 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:js="clr-namespace:MyProject" mc:Ignorable="d" x:Name="MyControlRootLayout" Background="Transparent" d:DesignHeight="300" d:DesignWidth="300" Cursor="Hand"> <Border x:Name="RootBorder" Background="{Binding Path=CoreBackground, ElementName=MyControlRootLayout}" > </Border> </UserControl> And the code... public partial class MyControl : UserControl { public static DependencyProperty IsSelectedProperty = DependencyProperty.Register("IsSelected", typeof(bool), typeof(MyControl)); public static DependencyProperty CoreBackgroundProperty = DependencyProperty.Register("CoreBackground", typeof(Brush), typeof(MyControl)); public MyControl() { CoreBackground = new SolidColorBrush(Color.FromArgb(0, 255, 245, 104)); InitializeComponent(); Margin = new Thickness(5); } public Brush CoreBackground { get { return (Brush)GetValue(CoreBackgroundProperty); } set { SetValue(CoreBackgroundProperty, value); } } public bool IsSelected { get { return (bool)GetValue(IsSelectedProperty); } private set { SetValue(IsSelectedProperty, value); } } } Instead, the background comes out as transparent.

    Read the article

  • Bind an Incode DataTemplate in WPF

    - by Mike Bynum
    I have a WPF Application which is using MVVM. I know that there ways of doing this in XAML but I am working on a plugin architecture and came up with a solution where a plugin exposes it's viewmodel to my plugin host's viewmodel and it's datatemplate. I want to leave the lifetime management of the plugin view up to WPF. I have tried having the plugins expose a UserControl but ran into issues when WPF decided to dispose of my UserControl so I would not reattach it without weird hacky work arounds. I am having issues getting some sort of binding working to where i can bind a control to the data and it's template to my data template. I have a ViewModel which looks something like: public class MyViewModel { public DataTemplate SelectedTemplate{ get; set;} public object SelectedViewModel {get; set;} } The selected template and viewmodel are determined somewhere else in the code but are irrelevant to my question. My question is how i can bind to a DataTemplate so that I know how to display the data shown in the SelectedViewModel. The DataTemplate is a DataTemplate created incode which respresents: <DataTemplate DataType="{x:Type vm:MyViewModel}"> <v:MyUserControl /> </DataTemplate> I have tried: <UserControl Template="{Binding Path=SelectedTemplate}" Content="{Binding Path=SelectedViewModel"} /> But UserControl expects a control template and not a data template.

    Read the article

  • Part 3 of 4 : Tips/Tricks for Silverlight Developers.

    - by mbcrump
    Part 1 | Part 2 | Part 3 | Part 4 I wanted to create a series of blog post that gets right to the point and is aimed specifically at Silverlight Developers. The most important things I want this series to answer is : What is it?  Why do I care? How do I do it? I hope that you enjoy this series. Let’s get started: Tip/Trick #11) What is it? Underline Text in a TextBlock. Why do I care? I’ve seen people do some crazy things to get underlined text in a Silverlight Application. In case you didn’t know there is a property for that. How do I do it: On a TextBlock you have a property called TextDecorations. You can easily set this property in XAML or CodeBehind with the following snippet: <UserControl x:Class="SilverlightApplication19.MainPage" 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"> <TextBlock Name="txtTB" Text="MichaelCrump.NET" TextDecorations="Underline" /> </Grid> </UserControl> or you can do it in CodeBehind… txtTB.TextDecorations = TextDecorations.Underline;   Tip/Trick #12) What is it? Get the browser information from a Silverlight Application. Why do I care? This will allow you to program around certain browser conditions that otherwise may not be aware of. How do I do it: It is very easy to extract Browser Information out a Silverlight Application by using the BrowserInformation class. You can copy/paste this code snippet to have access to all of them. string strBrowserName = HtmlPage.BrowserInformation.Name; string strBrowserMinorVersion = HtmlPage.BrowserInformation.BrowserVersion.Minor.ToString(); string strIsCookiesEnabled = HtmlPage.BrowserInformation.CookiesEnabled.ToString(); string strPlatform = HtmlPage.BrowserInformation.Platform; string strProductName = HtmlPage.BrowserInformation.ProductName; string strProductVersion = HtmlPage.BrowserInformation.ProductVersion; string strUserAgent = HtmlPage.BrowserInformation.UserAgent; string strBrowserVersion = HtmlPage.BrowserInformation.BrowserVersion.ToString(); string strBrowserMajorVersion = HtmlPage.BrowserInformation.BrowserVersion.Major.ToString(); Tip/Trick #13) What is it? Always check the minRuntimeVersion after creating a new Silverlight Application. Why do I care? Whenever you create a new Silverlight Application and host it inside of an ASP.net website you will notice Visual Studio generates some code for you as shown below. The minRuntimeVersion value is set by the SDK installed on your system. Be careful, if you are playing with beta’s like “Lightswitch” because you will have a higher version of the SDK installed. So when you create a new Silverlight 4 project and deploy it your customers they will get a prompt telling them they need to upgrade Silverlight. They also will not be able to upgrade to your version because its not released to the public yet. How do I do it: Open up the .aspx or .html file Visual Studio generated and look for the line below. Make sure it matches whatever version you are actually targeting. Tip/Trick #14) What is it? The VisualTreeHelper class provides useful methods for involving nodes in a visual tree. Why do I care? It’s nice to have the ability to “walk” a visual tree or to get the rendered elements of a ListBox. I have it very useful for debugging my Silverlight application. How do I do it: Many examples exist on the web, but say that you have a huge Silverlight application and want to find the parent object of a control.  In the code snippet below, we would get 3 MessageBoxes with (StackPanel first, Grid second and UserControl Third). This is a tiny application, but imagine how helpful this would be on a large project. <UserControl x:Class="SilverlightApplication18.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"> <StackPanel> <Button Content="Button" Height="23" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" /> </StackPanel> </Grid> </UserControl> private void button1_Click(object sender, RoutedEventArgs e) { DependencyObject obj = button1; while ((obj = VisualTreeHelper.GetParent(obj)) != null) { MessageBox.Show(obj.GetType().ToString()); } } Tip/Trick #15) What is it? Add ChildWindows to your Silverlight Application. Why do I care? ChildWindows are a great way to direct a user attention to a particular part of your application. This could be used when saving or entering data. How do I do it: Right click your Silverlight Application and click Add then New Item. Select Silverlight Child Window as shown below. Add an event and call the ChildWindow with the following snippet below: private void button1_Click(object sender, RoutedEventArgs e) { ChildWindow1 cw = new ChildWindow1(); cw.Show(); } Your main application can still process information but this screen forces the user to select an action before proceeding. The code behind of the ChildWindow will look like the following: namespace SilverlightApplication18 { public partial class ChildWindow1 : ChildWindow { public ChildWindow1() { InitializeComponent(); } private void OKButton_Click(object sender, RoutedEventArgs e) { this.DialogResult = true; //TODO: Add logic to save what the user entered. } private void CancelButton_Click(object sender, RoutedEventArgs e) { this.DialogResult = false; } } } Thanks for reading and please come back for Part 4.  Subscribe to my feed CodeProject

    Read the article

  • Silverlight MouseLeftButtonDown event not firing

    - by Matt
    For the life of me, I can not get this to work. I can get MouseEnter, MouseLeave, and Click events to fire, but not MouseLeftButtonDown or MouseLeftButtonUp. Here's my XAML <UserControl x:Class="Dive.Map.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" > <Canvas x:Name="LayoutRoot" MouseLeftButtonDown="LayoutRoot_MouseLeftButtonDown"> <Button x:Name="btnTest" Content="asdf" Background="Transparent" MouseLeftButtonDown="btnTest_MouseLeftButtonDown"></Button> </Canvas> </UserControl> And here's my code public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); } private void btnTest_MouseLeftButtonDown( object sender, MouseButtonEventArgs e ) { btnTest.Content = DateTime.Now.ToString(); } private void LayoutRoot_MouseLeftButtonDown( object sender, MouseButtonEventArgs e ) { e.Handled = false; } } What am I doing wrong?

    Read the article

  • Query on MVVM design pattern on WPF.

    - by Ashish Ashu
    I am using MVVM architecture. I have a usercontrol UC as a View Model is a ModelData class ViewModel (UCViewModel) is binded to a usercontrol. I have three more usercontrols that is inside the usercontrol UC ( discussed above). Let's say uc1, uc2 and uc3. and the visibility of uc1 , uc2 and uc3 inside UC depends on the type selected ( which ever radio button is selected ). Since UC is binded to UCViewModel and I have to do all the stuff related to uc1 , uc2 and uc3 inside UCViewModel. Can I have seperate VM to uc1 , uc2 and uc3.. if Yes how can i do that ? Please Help!!

    Read the article

  • Problem with Popup.StaysOpen in WPF

    - by Tola Ch.
    I got my UserControl that contain: Button Popup (contain Text block) XAML <UserControl> <button Name="btnShowPopup" Content="Button" Click="Button_Click"/> <Popup Name="popup" StaysOpen="true"> <TextBlock Text="Popup"/> </Popup> </UserControl> Code Behide private void Button_Click(object sender, System.Windows.RoutedEventArgs e) { this.popup.IsOpen=!this.popup.IsOpen; } QUESTION: I want to hide the popup, when mouse click on anywhere outside the btnShowPopup button. NOTE: I tried change StaysOpen="false" and when btnShowPopup.MouseDown event: this.popup.IsOpen=!this.popup.IsOpen; But this solution cause another problem: when btnShowPopup.MouseUp event, the Popup is disappear. Please help.

    Read the article

  • WPF Binding issues

    - by Nitin Chaudhari
    I have WPF window which binds a local Dependency property to a property of my usercontrol. So now I see the value which the window gave me in my usercontrol. I achieve this by setting DataContext of window to the window itself Now once the window is loaded i set the DataContext of usercontrol to a ViewModel class, and at some point of time(based on user action) the control changes values in the control. All fine so far. But now the changed value is not reflected in Windows dependency property. How I can resolve this issue?

    Read the article

  • [XAML] datatrigger

    - by Bert
    Hi, I have a UserControl in XAML with a couple of buttons.... When the "VideoEnable" property in my C# code change to true i want to change the color of a button. The following code compiles but crashes and I cant find a right solution <UserControl.Triggers> <DataTrigger Binding="{Binding VideoEnable}" Value="true"> <Setter Property="Button.Background" Value="Green" TargetName="VideoButton" /> <Setter Property="Grid.Background" Value="Blue" TargetName="videoGrid" /> </DataTrigger> </UserControl.Triggers>

    Read the article

  • F#: Define an abstract class that inherits an infterface, but does not implement it

    - by akaphenom
    I owuld like to define an abstract class that inerhits from UserControl and my own Interface IUriProvider, but doesn't implement it. The goal is to be able to define pages (for silverlight) that implement UserControl but also provide their own Uri's (and then stick them in a list / array and deal with them as a set: type IUriProvider = interface abstract member uriString: String ; abstract member Uri : unit -> System.Uri ; end type UriUserControl() as this = inherit IUriProvider with abstract member uriString: String ; inherit UserControl() Also the Uri in the definition - I would like to implement as a property getter - and am having issues with that as well. this does not compile type IUriProvider = interface abstract member uriString: String with get; end Thank you...

    Read the article

  • redirect an event in VB.NET

    - by serhio
    I havea a UserControl1 (in witch I have an Label1) in Form1. I want to catch the MouseDown event from label and send it like from UserControl I do: Public Class UserControl1 Shadows Custom Event MouseDown As MouseEventHandler AddHandler(ByVal value As MouseEventHandler) AddHandler Label1.MouseDown, value End AddHandler RemoveHandler(ByVal value As MouseEventHandler) RemoveHandler Label1.MouseDown, value End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As MouseEventArgs) 'RaiseMouseEvent(Me, e) ??? ' End RaiseEvent End Event End Class However, when I set in the Form1 the UserControl Private Sub UserControl11_MouseDown(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.MouseEventArgs) _ Handles UserControl11.MouseDown MessageBox.Show(sender.GetType.Name) 'here I have 'Label', want 'UserControl' End Sub

    Read the article

  • The property 'IsDataSource' was not found in type 'ViewModelLocator

    - by dieter-preconsult-be
    Hello I have the following code: <UserControl x:Class="TestApp.View.ViewAlarmLog" 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:Custom="http://schemas.microsoft.com/wpf/2008/toolkit" xmlns:mvvm="clr-namespace:Test.ViewModel"> <UserControl.Resources> <ResourceDictionary > <ResourceDictionary.MergedDictionaries> </ResourceDictionary.MergedDictionaries> <mvvm:ViewModelLocator x:Key="Locator" d:IsDataSource="True"/> </ResourceDictionary> </UserControl.Resources> the problem is dat i always get an error: The property 'IsDataSource' was not found in type 'ViewModelLocator'. " What could be the problem here ? Redgards Dieter

    Read the article

  • Adding Multiline html content using javascript

    - by pokrate
    Hi, I have created a usercontrol and I want to put its generated html using a javascript file in a webpage. But couldnt do so. Like <script src='file.aspx'></script> should add the html from the usercontrol to the container div. The file "file.aspx" has its content-type set to "text/javascript". And using LoadControl() method I am loading the usercontrol, and then using its RenderControl method, I am able to get its generated html. But I couldnt show it up in the webpage. But I am able to add single line html content , but multiline consumed my whole day :( .

    Read the article

  • Getting all types from an assembly derived from a base class

    - by CaptnCraig
    I am trying to examine the contents of an assembly and find all classes in it that are directly or indirectly derived from Windows.Forms.UserControl. I am doing this: Assembly dll = Assembly.LoadFrom(filename); var types = dll.GetTypes().Where(x => x.BaseType == typeof(UserControl)); But it is giving an empty list because none of the classes directly extend UserControl. I don't know enough about reflection to do it quickly, and I'd rather not write a recursive function if I don't have to.

    Read the article

  • how to access a label form user control in Parent class ?

    - by haansi
    I have a class UserControlBase that inherits System.Web.UI.UserControl and my user controls inherit UserControlBase class. UserControlBase has some common functions that are used in all user controls. I want to put error display funtion to UserControlBase as well so that I may not have to declare and manage it in all user controls. Error will be displayed in some label in usercontrol. Issue is how to access label which is in usercontrol in UserControlBase in function ? I dont want to pass label as argument. Please guide me on this issue. thanks

    Read the article

  • XamlXmlReader.Read() does not yield matching XamlNodeType.StartObject and XamlNodeType.EndObject on

    - by Yuval
    Hi, I am trying to parse a valid xaml file using the XamlXmlReader. It looks like it is 'skipping' some elements when when Read() is called. for example on the following xaml snippet: <UserControl.Resources> <Converters:AnyDbTypeToDisplayNameConverter x:Key="anyDbTypeToDisplayNameConverter" /> </UserControl.Resources> when reading I first get a XamlNodeType.StartObject on UserControl.Resources - makes sense then another XamlNodeType.StartObject on Converters - also cool. but then i do not get a XamlNodeType.EndObject on the Converters and immediately jump to the next line and does not report a XamlNodeType.StartObject. Any Idea if this is working as design ? looks like a bug to me

    Read the article

  • How to organize architecture WPF project?

    - by Dmitriy
    Hello! In my WPF project i want to have only one Window - MainWindow and UserControls as working part. I have some little different applications in one, and want to make navigation on top of my MainWindow as buttons. And little applications as UserControl. In MainWindow - grid with Big Empty Zone - which use to keep and run work. But, i want to navigate to other userControl from another. (probably do not understand :() How organize architecture WPF project that: one main window and many usercontrols which places in mainwindow and replace each other in turn. and there is the possibility of navigating from another usercontrol to another. May be it's MVVM, but i don't understand how this pattern can help me.

    Read the article

  • Accessing "current class" from WPF custom MarkupExtension

    - by chaiguy
    I'm attempting to write a custom MarkupExtension to make my life easier by giving me a better way to specify bindings in XAML. However I would like to know if there is any way I can access the object that represents the file the MarkupExtension is used in. In other words, suppose I have a UserControl that defines a particular rendition of a data model of my program. This control has lots of visual stuff like grids, borders and general layout. If I use my MarkupExtension on a particular property of some element in this UserControl, I want to access the instance of the UserControl, without knowing what type it is (I plan on using reflection). Is this at all possible?

    Read the article

  • WPF: Custom control that binds its content to a label

    - by nialsh
    I want to write a custom control that's used like this: <HorizontalTick>Some string</HorizontalTick> It should render like this: -- Some string ------------------------------------------- Here's my code: <UserControl x:Class="WeatherDownloadDisplay.View.HorizontalTick" 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" mc:Ignorable="d" d:DesignWidth="348" Name="controlRoot"> <DockPanel LastChildFill="True"> <UserControl VerticalAlignment="Center" BorderBrush="Black" BorderThickness="1" Width="10"/> <Label Content="???" /> <UserControl VerticalAlignment="Center" BorderBrush="Black" BorderThickness="1"/> </DockPanel> It works except for the label binding. Can someone help me fill in the question marks? I thought about using a ContentPresenter but it seems like an inline binding would be best. -Neal

    Read the article

  • Where best to instantiate and close a Silverlight-enabled WCF Service from the Silverlight app?

    - by Yttrium
    When using a Silverlight-enabled WCF service, where is the best place to instantiate the service and to call the CloseAsync() method? Should you say, instantiate an instance each time you need to make a call to the service, or is it better to just instantiate an instance as a variable of the UserControl that will be making the calls? Then, where is it better to call the CloseAsync method? Should you call it in each of the "someServiceCall_completed" event methods? Or, if created as a variable of the UserControl class, is there a single place to call it? Like a Dispose method, or something equivalent for the UserControl class. Thanks, Jeff

    Read the article

  • assembly.GetTypes() does not return all types

    - by meta
    I try to lead the types from an .dll (which is also referenced in the executing project). I call: public static void LoadPlugin(string pluginFile) { Assembly assembly = Assembly.LoadFrom(pluginFile); foreach (Type type in assembly.GetTypes()) { // play with it } } It loads just a few of them: public partial class Mathematics : UserControl, IMathematics, IPortable and public partial class Welcome : UserControl but the next one, and some others, are ignored: public partial class Test : UserControl, ITest, IPortable They all stand in the same assembly, under the same namespace. The public static void LoadPlugin(string pluginFile) method is located in other assembly that is also referenced in the executing project. No exceptions are thrown. What could be the issues for not loading all the types? Any ideas?

    Read the article

  • How to use multiple restrictions in C# Generics properly?

    - by plouh
    I am attempting to bind c# generics to a class and an interface like this: public class WizardPage<T> where T : UserControl, IWizardControl { private T page; public WizardPage( T page ) { this.page = page; } } And use it with this: public MyControl : UserControl, IWizardControl { //... } Somehow C# doesn't seem to be able to decide that MyControl is a proper instance of T as public class Wizard<T> where T : UserControl, IWizardControl { private WizardPage<T> Page1; public Wizard( MyControl control ) { this.Page1 = new WizardPage(control); } } fails with error The best overloaded method match for 'Controls.WizardPage.WizardPage(T)' has some invalid arguments Am I doing something wrong or is this just not going to work?

    Read the article

  • Introducing the Earthquake Locator – A Bing Maps Silverlight Application, part 1

    - by Bobby Diaz
    Update: Live demo and source code now available!  The recent wave of earthquakes (no pun intended) being reported in the news got me wondering about the frequency and severity of earthquakes around the world. Since I’ve been doing a lot of Silverlight development lately, I decided to scratch my curiosity with a nice little Bing Maps application that will show the location and relative strength of recent seismic activity. Here is a list of technologies this application will utilize, so be sure to have everything downloaded and installed if you plan on following along. Silverlight 3 WCF RIA Services Bing Maps Silverlight Control * Managed Extensibility Framework (optional) MVVM Light Toolkit (optional) log4net (optional) * If you are new to Bing Maps or have not signed up for a Developer Account, you will need to visit www.bingmapsportal.com to request a Bing Maps key for your application. Getting Started We start out by creating a new Silverlight Application called EarthquakeLocator and specify that we want to automatically create the Web Application Project with RIA Services enabled. I cleaned up the web app by removing the Default.aspx and EarthquakeLocatorTestPage.html. Then I renamed the EarthquakeLocatorTestPage.aspx to Default.aspx and set it as my start page. I also set the development server to use a specific port, as shown below. RIA Services Next, I created a Services folder in the EarthquakeLocator.Web project and added a new Domain Service Class called EarthquakeService.cs. This is the RIA Services Domain Service that will provide earthquake data for our client application. I am not using LINQ to SQL or Entity Framework, so I will use the <empty domain service class> option. We will be pulling data from an external Atom feed, but this example could just as easily pull data from a database or another web service. This is an important distinction to point out because each scenario I just mentioned could potentially use a different Domain Service base class (i.e. LinqToSqlDomainService<TDataContext>). Now we can start adding Query methods to our EarthquakeService that pull data from the USGS web site. Here is the complete code for our service class: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.ServiceModel.Syndication; using System.Web.DomainServices; using System.Web.Ria; using System.Xml; using log4net; using EarthquakeLocator.Web.Model;   namespace EarthquakeLocator.Web.Services {     /// <summary>     /// Provides earthquake data to client applications.     /// </summary>     [EnableClientAccess()]     public class EarthquakeService : DomainService     {         private static readonly ILog log = LogManager.GetLogger(typeof(EarthquakeService));           // USGS Data Feeds: http://earthquake.usgs.gov/earthquakes/catalogs/         private const string FeedForPreviousDay =             "http://earthquake.usgs.gov/earthquakes/catalogs/1day-M2.5.xml";         private const string FeedForPreviousWeek =             "http://earthquake.usgs.gov/earthquakes/catalogs/7day-M2.5.xml";           /// <summary>         /// Gets the earthquake data for the previous week.         /// </summary>         /// <returns>A queryable collection of <see cref="Earthquake"/> objects.</returns>         public IQueryable<Earthquake> GetEarthquakes()         {             var feed = GetFeed(FeedForPreviousWeek);             var list = new List<Earthquake>();               if ( feed != null )             {                 foreach ( var entry in feed.Items )                 {                     var quake = CreateEarthquake(entry);                     if ( quake != null )                     {                         list.Add(quake);                     }                 }             }               return list.AsQueryable();         }           /// <summary>         /// Creates an <see cref="Earthquake"/> object for each entry in the Atom feed.         /// </summary>         /// <param name="entry">The Atom entry.</param>         /// <returns></returns>         private Earthquake CreateEarthquake(SyndicationItem entry)         {             Earthquake quake = null;             string title = entry.Title.Text;             string summary = entry.Summary.Text;             string point = GetElementValue<String>(entry, "point");             string depth = GetElementValue<String>(entry, "elev");             string utcTime = null;             string localTime = null;             string depthDesc = null;             double? magnitude = null;             double? latitude = null;             double? longitude = null;             double? depthKm = null;               if ( !String.IsNullOrEmpty(title) && title.StartsWith("M") )             {                 title = title.Substring(2, title.IndexOf(',')-3).Trim();                 magnitude = TryParse(title);             }             if ( !String.IsNullOrEmpty(point) )             {                 var values = point.Split(' ');                 if ( values.Length == 2 )                 {                     latitude = TryParse(values[0]);                     longitude = TryParse(values[1]);                 }             }             if ( !String.IsNullOrEmpty(depth) )             {                 depthKm = TryParse(depth);                 if ( depthKm != null )                 {                     depthKm = Math.Round((-1 * depthKm.Value) / 100, 2);                 }             }             if ( !String.IsNullOrEmpty(summary) )             {                 summary = summary.Replace("</p>", "");                 var values = summary.Split(                     new string[] { "<p>" },                     StringSplitOptions.RemoveEmptyEntries);                   if ( values.Length == 3 )                 {                     var times = values[1].Split(                         new string[] { "<br>" },                         StringSplitOptions.RemoveEmptyEntries);                       if ( times.Length > 0 )                     {                         utcTime = times[0];                     }                     if ( times.Length > 1 )                     {                         localTime = times[1];                     }                       depthDesc = values[2];                     depthDesc = "Depth: " + depthDesc.Substring(depthDesc.IndexOf(":") + 2);                 }             }               if ( latitude != null && longitude != null )             {                 quake = new Earthquake()                 {                     Id = entry.Id,                     Title = entry.Title.Text,                     Summary = entry.Summary.Text,                     Date = entry.LastUpdatedTime.DateTime,                     Url = entry.Links.Select(l => Path.Combine(l.BaseUri.OriginalString,                         l.Uri.OriginalString)).FirstOrDefault(),                     Age = entry.Categories.Where(c => c.Label == "Age")                         .Select(c => c.Name).FirstOrDefault(),                     Magnitude = magnitude.GetValueOrDefault(),                     Latitude = latitude.GetValueOrDefault(),                     Longitude = longitude.GetValueOrDefault(),                     DepthInKm = depthKm.GetValueOrDefault(),                     DepthDesc = depthDesc,                     UtcTime = utcTime,                     LocalTime = localTime                 };             }               return quake;         }           private T GetElementValue<T>(SyndicationItem entry, String name)         {             var el = entry.ElementExtensions.Where(e => e.OuterName == name).FirstOrDefault();             T value = default(T);               if ( el != null )             {                 value = el.GetObject<T>();             }               return value;         }           private double? TryParse(String value)         {             double d;             if ( Double.TryParse(value, out d) )             {                 return d;             }             return null;         }           /// <summary>         /// Gets the feed at the specified URL.         /// </summary>         /// <param name="url">The URL.</param>         /// <returns>A <see cref="SyndicationFeed"/> object.</returns>         public static SyndicationFeed GetFeed(String url)         {             SyndicationFeed feed = null;               try             {                 log.Debug("Loading RSS feed: " + url);                   using ( var reader = XmlReader.Create(url) )                 {                     feed = SyndicationFeed.Load(reader);                 }             }             catch ( Exception ex )             {                 log.Error("Error occurred while loading RSS feed: " + url, ex);             }               return feed;         }     } }   The only method that will be generated in the client side proxy class, EarthquakeContext, will be the GetEarthquakes() method. The reason being that it is the only public instance method and it returns an IQueryable<Earthquake> collection that can be consumed by the client application. GetEarthquakes() calls the static GetFeed(String) method, which utilizes the built in SyndicationFeed API to load the external data feed. You will need to add a reference to the System.ServiceModel.Web library in order to take advantage of the RSS/Atom reader. The API will also allow you to create your own feeds to serve up in your applications. Model I have also created a Model folder and added a new class, Earthquake.cs. The Earthquake object will hold the various properties returned from the Atom feed. Here is a sample of the code for that class. Notice the [Key] attribute on the Id property, which is required by RIA Services to uniquely identify the entity. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ComponentModel.DataAnnotations;   namespace EarthquakeLocator.Web.Model {     /// <summary>     /// Represents an earthquake occurrence and related information.     /// </summary>     [DataContract]     public class Earthquake     {         /// <summary>         /// Gets or sets the id.         /// </summary>         /// <value>The id.</value>         [Key]         [DataMember]         public string Id { get; set; }           /// <summary>         /// Gets or sets the title.         /// </summary>         /// <value>The title.</value>         [DataMember]         public string Title { get; set; }           /// <summary>         /// Gets or sets the summary.         /// </summary>         /// <value>The summary.</value>         [DataMember]         public string Summary { get; set; }           // additional properties omitted     } }   View Model The recent trend to use the MVVM pattern for WPF and Silverlight provides a great way to separate the data and behavior logic out of the user interface layer of your client applications. I have chosen to use the MVVM Light Toolkit for the Earthquake Locator, but there are other options out there if you prefer another library. That said, I went ahead and created a ViewModel folder in the Silverlight project and added a EarthquakeViewModel class that derives from ViewModelBase. Here is the code: using System; using System.Collections.ObjectModel; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using Microsoft.Maps.MapControl; using GalaSoft.MvvmLight; using EarthquakeLocator.Web.Model; using EarthquakeLocator.Web.Services;   namespace EarthquakeLocator.ViewModel {     /// <summary>     /// Provides data for views displaying earthquake information.     /// </summary>     public class EarthquakeViewModel : ViewModelBase     {         [Import]         public EarthquakeContext Context;           /// <summary>         /// Initializes a new instance of the <see cref="EarthquakeViewModel"/> class.         /// </summary>         public EarthquakeViewModel()         {             var catalog = new AssemblyCatalog(GetType().Assembly);             var container = new CompositionContainer(catalog);             container.ComposeParts(this);             Initialize();         }           /// <summary>         /// Initializes a new instance of the <see cref="EarthquakeViewModel"/> class.         /// </summary>         /// <param name="context">The context.</param>         public EarthquakeViewModel(EarthquakeContext context)         {             Context = context;             Initialize();         }           private void Initialize()         {             MapCenter = new Location(20, -170);             ZoomLevel = 2;         }           #region Private Methods           private void OnAutoLoadDataChanged()         {             LoadEarthquakes();         }           private void LoadEarthquakes()         {             var query = Context.GetEarthquakesQuery();             Context.Earthquakes.Clear();               Context.Load(query, (op) =>             {                 if ( !op.HasError )                 {                     foreach ( var item in op.Entities )                     {                         Earthquakes.Add(item);                     }                 }             }, null);         }           #endregion Private Methods           #region Properties           private bool autoLoadData;         /// <summary>         /// Gets or sets a value indicating whether to auto load data.         /// </summary>         /// <value><c>true</c> if auto loading data; otherwise, <c>false</c>.</value>         public bool AutoLoadData         {             get { return autoLoadData; }             set             {                 if ( autoLoadData != value )                 {                     autoLoadData = value;                     RaisePropertyChanged("AutoLoadData");                     OnAutoLoadDataChanged();                 }             }         }           private ObservableCollection<Earthquake> earthquakes;         /// <summary>         /// Gets the collection of earthquakes to display.         /// </summary>         /// <value>The collection of earthquakes.</value>         public ObservableCollection<Earthquake> Earthquakes         {             get             {                 if ( earthquakes == null )                 {                     earthquakes = new ObservableCollection<Earthquake>();                 }                   return earthquakes;             }         }           private Location mapCenter;         /// <summary>         /// Gets or sets the map center.         /// </summary>         /// <value>The map center.</value>         public Location MapCenter         {             get { return mapCenter; }             set             {                 if ( mapCenter != value )                 {                     mapCenter = value;                     RaisePropertyChanged("MapCenter");                 }             }         }           private double zoomLevel;         /// <summary>         /// Gets or sets the zoom level.         /// </summary>         /// <value>The zoom level.</value>         public double ZoomLevel         {             get { return zoomLevel; }             set             {                 if ( zoomLevel != value )                 {                     zoomLevel = value;                     RaisePropertyChanged("ZoomLevel");                 }             }         }           #endregion Properties     } }   The EarthquakeViewModel class contains all of the properties that will be bound to by the various controls in our views. Be sure to read through the LoadEarthquakes() method, which handles calling the GetEarthquakes() method in our EarthquakeService via the EarthquakeContext proxy, and also transfers the loaded entities into the view model’s Earthquakes collection. Another thing to notice is what’s going on in the default constructor. I chose to use the Managed Extensibility Framework (MEF) for my composition needs, but you can use any dependency injection library or none at all. To allow the EarthquakeContext class to be discoverable by MEF, I added the following partial class so that I could supply the appropriate [Export] attribute: using System; using System.ComponentModel.Composition;   namespace EarthquakeLocator.Web.Services {     /// <summary>     /// The client side proxy for the EarthquakeService class.     /// </summary>     [Export]     public partial class EarthquakeContext     {     } }   One last piece I wanted to point out before moving on to the user interface, I added a client side partial class for the Earthquake entity that contains helper properties that we will bind to later: using System;   namespace EarthquakeLocator.Web.Model {     /// <summary>     /// Represents an earthquake occurrence and related information.     /// </summary>     public partial class Earthquake     {         /// <summary>         /// Gets the location based on the current Latitude/Longitude.         /// </summary>         /// <value>The location.</value>         public string Location         {             get { return String.Format("{0},{1}", Latitude, Longitude); }         }           /// <summary>         /// Gets the size based on the Magnitude.         /// </summary>         /// <value>The size.</value>         public double Size         {             get { return (Magnitude * 3); }         }     } }   View Now the fun part! Usually, I would create a Views folder to place all of my View controls in, but I took the easy way out and added the following XAML code to the default MainPage.xaml file. Be sure to add the bing prefix associating the Microsoft.Maps.MapControl namespace after adding the assembly reference to your project. The MVVM Light Toolkit project templates come with a ViewModelLocator class that you can use via a static resource, but I am instantiating the EarthquakeViewModel directly in my user control. I am setting the AutoLoadData property to true as a way to trigger the LoadEarthquakes() method call. The MapItemsControl found within the <bing:Map> control binds its ItemsSource property to the Earthquakes collection of the view model, and since it is an ObservableCollection<T>, we get the automatic two way data binding via the INotifyCollectionChanged interface. <UserControl x:Class="EarthquakeLocator.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"     xmlns:bing="clr-namespace:Microsoft.Maps.MapControl;assembly=Microsoft.Maps.MapControl"     xmlns:vm="clr-namespace:EarthquakeLocator.ViewModel"     mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480" >     <UserControl.Resources>         <DataTemplate x:Key="EarthquakeTemplate">             <Ellipse Fill="Red" Stroke="Black" StrokeThickness="1"                      Width="{Binding Size}" Height="{Binding Size}"                      bing:MapLayer.Position="{Binding Location}"                      bing:MapLayer.PositionOrigin="Center">                 <ToolTipService.ToolTip>                     <StackPanel>                         <TextBlock Text="{Binding Title}" FontSize="14" FontWeight="Bold" />                         <TextBlock Text="{Binding UtcTime}" />                         <TextBlock Text="{Binding LocalTime}" />                         <TextBlock Text="{Binding DepthDesc}" />                     </StackPanel>                 </ToolTipService.ToolTip>             </Ellipse>         </DataTemplate>     </UserControl.Resources>       <UserControl.DataContext>         <vm:EarthquakeViewModel AutoLoadData="True" />     </UserControl.DataContext>       <Grid x:Name="LayoutRoot">           <bing:Map x:Name="map" CredentialsProvider="--Your-Bing-Maps-Key--"                   Center="{Binding MapCenter, Mode=TwoWay}"                   ZoomLevel="{Binding ZoomLevel, Mode=TwoWay}">             <bing:MapItemsControl ItemsSource="{Binding Earthquakes}"                                   ItemTemplate="{StaticResource EarthquakeTemplate}" />         </bing:Map>       </Grid> </UserControl>   The EarthquakeTemplate defines the Ellipse that will represent each earthquake, the Width and Height that are determined by the Magnitude, the Position on the map, and also the tooltip that will appear when we mouse over each data point. Running the application will give us the following result (shown with a tooltip example): That concludes this portion of our show but I plan on implementing additional functionality in later blog posts. Be sure to come back soon to see the next installments in this series. Enjoy!   Additional Resources USGS Earthquake Data Feeds Brad Abrams shows how RIA Services and MVVM can work together

    Read the article

  • Extending Expression Blend 4 &amp; Blend for Visual Studio 2012

    - by Chris Skardon
    Just getting this off the bat, I presume this will also work for Blend 5, but I can’t confirm it… Anyhews, I imagine you’re here because you want to know how to create an addin for Blend, so let’s jump right in there! First, and foremost, we’re going to need to ensure our development environment has the right setup, so the checklist: Visual Studio 2012 Blend for Visual Studio 2012 OK, let’s create a new project (class library, .NET 4.5): Hello.Extension The ‘.Extension’ bit is very very important. The addin will not work unless it is named in this way. You can put whatever you want at the front, but it has to have the extension bit. OK, so now we have a solution with one project. To this project we need to add references to the following things: Microsoft.Expression.Extensibility (from c:\program files\Microsoft Visual Studio 11.0\Blend\   -- x86 folder if you are on an x64 windows install) Microsoft.Expression.Framework (same location as above) PresentationCore PresentationFramework WindowsBase System.ComponentModel.Composition Got them? ACE. Let’s now add a project to contain our control, so, create a new WPF Application project, cunningly named something like ‘Hello.Control’… (I’m creating a WPF application here, because I’m too lazy to dig up the correct references, and this will add all the ones I need ) Once that is created, delete the App.xaml and MainWindow.xaml files, we won’t be needing them. You will also need to change the properties of the project itself, so it is only a class library. Once that is done, let’s add a new UserControl, which will be this: <UserControl x:Class="Hello.Control.HelloControl" 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" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <Grid> <TextBlock Text="HELLO!!!"/> </Grid> </UserControl> Impressive eh? Now, let’s reference the WPF project from the Extension library. All that’s left now is to code up our extension… So, add a class to the Extension project (name wise doesn’t matter), and make it implement the IPackage interface from the Microsoft.Expression.Extensibility library: public class HelloExtension : IPackage { /**/ } We’ll implement the two methods we need to: public class HelloExtension : IPackage { public void Load(IServices services) { } public void Unload() { } } We’re only really concerned about the Load method in this case, as let’s face it, the extension we have doesn’t need to do a lot to bog off. The interesting thing about the Load method is that it receives an IServices instance. This allows us to get access to all the services that Expression provides, in this case we’re interested in one in particular, the ‘IWindowService’ So, let’s get that bad boy… private IWindowService _windowService; public void Load(IServices services) { _windowService = services.GetService<IWindowService>(); } Nailed it… But why? The WindowService allows us to register our UserControl with Blend, which in turn allows people to activate and see it, which is a big plus point. So, let’s do that… We’ll create an ‘Initialize’ method to create our new control, and add it to the WindowService: private HelloControl _helloControl; public void Initialize() { _helloControl = new HelloControl(); if (_windowService.PaletteRegistry["HelloPanel"] == null) _windowService.RegisterPalette("HelloPanel", _helloControl, "Hello Window"); } First we check that we’re not already registered, and if we’re not we register, the first argument is the identifier used by the service to, well, identify your extension. The second argument is the actual control, the third argument is the name that people will see in the ‘Windows’ menu of Blend itself (so important note here – don’t put anything embarrassing or (need I say it?) sweary…) There are only two things to do now - Call ‘Initialize()’ from our Load method, and Export the class This is easy money – add [Export(typeof(IPackage))] to the top of our class… The full code will (should) look like this: [Export(typeof (IPackage))] public class HelloExtension : IPackage { private HelloControl _helloControl; private IWindowService _windowService; public void Load(IServices services) { _windowService = services.GetService<IWindowService>(); Initialize(); } public void Unload() { } public void Initialize() { _helloControl = new HelloControl(); if (_windowService.PaletteRegistry["HelloControl"] == null) _windowService.RegisterPalette("HelloControl", _helloControl, "Hello Window"); } } If you build this and copy it to your ‘Extensions’ folder in Blend (c:\program files\microsoft visual studio 11.0\blend\) and start Blend, you should see ‘Hello Window’ listed in the Window menu: That as they say is it!

    Read the article

< Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >