Search Results

Search found 10936 results on 438 pages for 'wpf controls'.

Page 2/438 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Working on WPF application Memory Profiling

    - by akjoshi
    Today, I am going to start with the task of memory profiling the WPF application, on which I am working from past few months. I have successfully done this in past, fixing a lot of memory leaks and improving the performance of WPF applications; As in past, I am hopeful of fixing some very interesting bugs and improve the application performance. I am very excited as current application is very different from the previous WPF applications I had profiled, all the previous application were pure WPF...(read more)

    Read the article

  • how to use multiple tab controls, and to be able to call a selected tab control with buttons.

    - by mojotaker
    Please I am trying to assign each button on the left its own Tab control. That is for example, when the Intake form button is pushed, it will have its own set of tabs (its own tabcontrols) am i supposed to place multiple tab controls on the artboard, or is there a way to programatically change the names of the tabs, and there contents, when a button is pushed on the left ? thank you in advance. and here is a link hxxp://img709.imageshack.us/img709/554/tabcontrol.gif here is the code so far <Window 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" x:Class="service.MainWindow" x:Name="Window" Title="MainWindow" Width="687" Height="480" mc:Ignorable="d"> <Window.Resources> <Storyboard x:Key="OnLoaded1"/> </Window.Resources> <Window.Triggers> <EventTrigger RoutedEvent="FrameworkElement.Loaded"> <BeginStoryboard Storyboard="{StaticResource OnLoaded1}"/> </EventTrigger> </Window.Triggers> <Grid x:Name="LayoutRoot" Margin="0,0,-16,1"> <Grid.ColumnDefinitions> <ColumnDefinition Width="0*"/> <ColumnDefinition/> </Grid.ColumnDefinitions> <DockPanel Margin="8,8,0,7" LastChildFill="False" Grid.Column="1" HorizontalAlignment="Left" Width="660"> <Menu VerticalAlignment="Top" Width="657" Height="32"> <MenuItem x:Name="file" Header="File"/> <MenuItem x:Name="edit" Header="Edit"> <MenuItem Width="100" Height="100" Header="MenuItem"/> </MenuItem> <MenuItem x:Name="view" Header="View"/> <MenuItem x:Name="preferences" Header="Preferences"/> <MenuItem x:Name="help" Header="Help"/> </Menu> </DockPanel> <TabControl x:Name="tabwin" Margin="137.224,46,19,7" Grid.Column="1"> <TabItem x:Name="intakeformsub" Header="Elegibility Form"> <Grid HorizontalAlignment="Left" Width="490"/> </TabItem> <TabItem Header="TabItem"> <Grid/> </TabItem> <TabItem Header="TabItem"> <Grid/> </TabItem> <TabItem Header="TabItem"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="0.567*"/> <ColumnDefinition Width="0.433*"/> </Grid.ColumnDefinitions> </Grid> </TabItem> <TabItem Header="TabItem"> <Grid/> </TabItem> <TabItem Header="TabItem"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="0.735*"/> <ColumnDefinition Width="0.265*"/> </Grid.ColumnDefinitions> </Grid> </TabItem> <TabItem Header="TabItem"> <Grid/> </TabItem> <TabItem Header="TabItem"> <Grid/> </TabItem> </TabControl> <Grid x:Name="___buttontab" Margin="11.205,61,0,0" Grid.Column="1" HorizontalAlignment="Left" Width="122.019" VerticalAlignment="Top" Height="276"> <Button VerticalAlignment="Top" Height="36" Content="Button"/> <Button Margin="0,40,0,0" Content="Oasis Assessments" VerticalAlignment="Top" Height="36"/> <Button Margin="0,80,0,0" VerticalAlignment="Top" Height="36" Content="Plan of Care"/> <Button Margin="0,120,0,0" VerticalAlignment="Top" Height="36" Content="Medication Profile" RenderTransformOrigin="0.421,5.556"/> <Button Margin="0,0,0,80" VerticalAlignment="Bottom" Height="36" Content="Clinical Notes"/> <Button Margin="0,0,0,40" VerticalAlignment="Bottom" Height="36" Content="Infection Control"/> <Button x:Name="intakeformbtn" VerticalAlignment="Top" Height="36" Content="Intake Form" Click="intakeform"> <Button.BindingGroup> <BindingGroup/> </Button.BindingGroup> </Button> <Button VerticalAlignment="Bottom" Height="36" Content="Discharge Summary"/> </Grid> <ProgressBar HorizontalAlignment="Left" Margin="8,0,0,7" VerticalAlignment="Bottom" Width="104.795" Height="19" Grid.Column="1"/> </Grid> </Window>

    Read the article

  • WPF and events from dynamically created controls

    - by OKB
    Hi, I need some help to implement a common behavior in some controls. In my WPF application, I have a main form that contains a panel and a button: Ok The button will run a Save method when clicked.The Save method reads some data from the form and saves the data to a database. The panel is populated with dynamically created controls (such as textbox, dropdownlists, etc). The main form instantiates a MainViewModel class. This MainViewModel class instantiates a class called UIFactory. So we have 3 levels here. In the UIFactory class the controls is being created. The Panel from the main form is sent as a parameter to a method in the MainModelView class called GenerateUI. This GenerateUI method in the MainViewModel class calls a GenerateControls method on the UIFactory class that takes the same panel as a parameter. The GenerateControls method in the UIFactory class then adds dynamically created controls on the panel. What I want to achieve is that whenever the user hits ENTER when he is typing in one of those dynamically created controls e.g a textbox, I want that behavior to be the same as clicking on the button in my main form. But how do I do that? I thought of implementing Routed events on my controls, but I can't figure out how to do it. Could you please advise me on how to achieve my goal? Best Regards, OKB

    Read the article

  • XAML Controls in WinForms

    - by Nathan Friesen
    We're considering converting our WinForms application to a WPF application. Part of the reason is that WPF/XAML seem to be the future. We are also using third party controls that we would like to be able to phase out. Making this conversion seems like a pretty big and time consuming undertaking, though. Would it make sense to develop XAML controls that could be used in our WinForms application as a first step in the process? My thinking is that the same controls would then be used in the WPF application and all of the look, feel, and functionality would be built into the controls in either environment.

    Read the article

  • Future of WPF and free controls ? [closed]

    - by Justin
    I am willing to work on a personal project that I would like to release publicly. I am working with Silverlight and have experience with XAML, as it is my full-time job. It is enjoyably for me to create UIs in Blend and XAML. I am also a big fan of C# language. I don't know what I would do without LINQ now. Anyways, I was looking at using WPF for my personal project. It seems that a lot of the controls out on the web are pay for items. The only place I have found to have a significant number of free controls is the WPF extended framework on codeplex. I want to make a financial application and need a powerful datagrid type of control that will allow me to enter transaction data. I haven't found such control for free in the net. It doesn't seem like there is much free community libraries/controls out there for Microsoft products. So, I was wondering if WPF would be the right way for me to go. I couldn't find any information on WPF usage in Windows 8, which coming very soon. I don't know Microsoft's plans for this technology. Would it be a better idea to use something different for the UI instead of WPF?

    Read the article

  • Moving from Winforms to WPF

    - by Elmex
    I am a long time experienced Windows Forms developer, but now it's time to move to WPF because a new WPF project is comming soon to me and I have only a short lead time to prepare myself to learn WPF. What is the best way for a experienced Winforms devleoper? Can you give me some hints and recommendations to learn WPF in a very short time! Are there simple sample WPF solutions and short (video) tutorials? Which books do you recommend? Is www.windowsclient.net a good starting point? Are there alternatives to the official Microsoft site? Thanks in advance for your help!

    Read the article

  • Moving from Winforms to WPF

    - by Elmex
    I am a long time experienced Windows Forms developer, but now it's time to move to WPF because a new WPF project is comming soon to me and I have only a short lead time to prepare myself to learn WPF. What is the best way for a experienced Winforms devleoper? Can you give me some hints and recommendations to learn WPF in a very short time! Are there simple sample WPF solutions and short (video) tutorials? Which books do you recommend? Is www.windowsclient.net a good starting point? Are there alternatives to the official Microsoft site? Thanks in advance for your help!

    Read the article

  • Is it possible for a WPF control to have an ActualWidth and ActualHeight if it has never been render

    - by DanM
    I need a Viewport3D for the sole purpose of doing geometric calculations using Petzold.Media3D.ViewportInfo. I do now want to place it in a Window. I'm creating a Viewport3D using the following code: private Viewport3D CreateViewport(MainSettings settings) { var cameraPosition = new Point3D(0, 0, settings.CameraHeight); var cameraLookDirection = new Vector3D(0, 0, -1); var cameraUpDirection = new Vector3D(0, 1, 0); var camera = new PerspectiveCamera { Position = cameraPosition, LookDirection = cameraLookDirection, UpDirection = cameraUpDirection }; var viewport = new Viewport3D { Camera = camera, Width = settings.ViewportWidth, Height = settings.ViewportHeight }; return viewport; } Later, I'm attempting to use this viewport to convert the mouse location to a 3D location using this method: public Point3D? Point2dToPoint3d(Point point) { var range = new LineRange(); var isValid = ViewportInfo.Point2DtoPoint3D(_viewport, point, out range); if (isValid) return range.PointFromZ(0); else return null; } Unfortunately, it's not working. I think the reason is that the ActualWidth and ActualHeight of the viewport and both zero (and these are read-only properties, so I can't set them manually). (I have tested the exact same with an actual rendered Viewport3D, so I know the issue is not with my converter method.) Any idea how I can get WPF to assign the ActualWidth and ActualHeight based on my Width and Height settings? I tried setting the HorizontalAlignment and VerticalAlignment to Left and Top, respectively, and I also messed with the MinWidth and MinHeight, but none of these properties had any effect on the ActualWidth or ActualHeight.

    Read the article

  • How do I get my custom WPF textbox to fill correctly?

    - by Dan Ryan
    I am trying to create a custom WPF textbox control that extends the standard textbox control but the extended textbox behaves differently when placed in control containers. Within my Window I have a stackpanel with a standard textbox and my extended textbox: <StackPanel Margin="10"> <TextBox Height="21" /> <l:SearchTextBox Search="SearchTextBox_Search" Height="21" Margin="0, 10, 0, 0" SearchMode="Delayed" HorizontalAlignment="Left" /> </StackPanel> The standard textbox stretches the length of the StackPanel whereas the custom textbox does not. How can I get the controls to behave the same? The styling for the custom textbox is shown below: <Style x:Key="{x:Type UIControls:SearchTextBox}" BasedOn="{StaticResource {x:Type TextBox}}" TargetType="{x:Type UIControls:SearchTextBox}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type UIControls:SearchTextBox}"> <TextBox /> </ControlTemplate> </Setter.Value> </Setter> </Style>

    Read the article

  • WPF Custom Control - Designer looks fine, but I get a runtime issue...

    - by myermian
    MainWindow.xaml <Window x:Class="MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:my="clr-namespace:MyStuff;assembly=MyStuff" Title="MainWindow" Height="350" Width="525"> <Grid> <TabControl Margin="5"> <TabItem Header="Start Page" /> <my:XTabItem Header="Tab 1" Image="Resources/icon1.png" /> </TabControl> </Grid> </Window> Generic.xaml <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:MyStuff" > <!-- XTabItem --> <Style TargetType="{x:Type local:XTabItem}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:XTabItem}"> <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <StackPanel Orientation="Horizontal"> <Image Source="{Binding Path=Image, RelativeSource={RelativeSource TemplatedParent}}" Stretch="UniformToFill" MaxHeight="24" /> <TextBlock Text="{TemplateBinding Header}" /> <Button Content="X" /> </StackPanel> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> XTabItem.cs using System; using System.ComponentModel; using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace MyStuff { public class XTabItem : TabItem { #region Dependency Properties public static readonly DependencyProperty ImageProperty; #endregion #region Constructors / Initializer static XTabItem() { //Initialize the control as "lookless". DefaultStyleKeyProperty.OverrideMetadata(typeof(XTabItem), new FrameworkPropertyMetadata(typeof(XTabItem))); //Setup the dependency properties. ImageProperty = DependencyProperty.Register("Image", typeof(ImageSource), typeof(XTabItem), new UIPropertyMetadata(null)); } #endregion #region Custom Control Properties (Image) /// <summary> /// The image (icon) displayed by inside the tab header. /// </summary> /// <remarks>The image is specified in XAML as an absolute or relative path.</remarks> [Description("The image displayed by the button"), Category("Optional Properties")] public ImageSource Image { get { return (ImageSource)GetValue(ImageProperty); } set { SetValue(ImageProperty, value); } } #endregion } } Exception at line #9 () : XamlParseException : 'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.' Line number '9' and line position '27'.

    Read the article

  • WPF Layout algorithm woes - control will resize, but not below some arbitrary value.

    - by Quantumplation
    I'm working on an application for a client, and one of the requirements is the ability to make appointments, and display the current week's appointments in a visual format, much like in Google Calender's or Microsoft Office. I found a great (3 part) article on codeproject, in which he builds a "RangePanel", and composes one for each "period" (for example, the work day.) You can find part 1 here: http://www.codeproject.com/KB/WPF/OutlookWpfCalendarPart1.aspx The code presents, but seems to choose an arbitrary height value overall (440.04), and won't resize below that without clipping. What I mean to say, is that the window/container will resize, but it just cuts off the bottom of the control, instead of recalculating the height of the range panels, and the controls in the range panels representing the appointment. It will resize and recalculate for greater values, but not less. Code-wise, what's happening is that when you resize below that value, first the "MeasureOverride" is called with the correct "new height". However, by the time the "ArrangeOverride" method is called, it's passing the same 440.04 value as the height to arrange to. I need to find a solution/workaround, but any information that you can provide that might direct me for things to look into would also be greatly appreciated ( I understand how frustrating it is to debug code when you don't have the codebase in front of you. :) ) The code for the various Arrange and Measure functions are provided below. The "CalendarView" control has a "CalendarViewContentPresenter", which handles several periods. Then, the periods have a "CalendarPeriodContentPresenter", which handles each "block" of appointments. Finally, the "RangePanel" has it's own implementation. (To be honest, i'm still a bit hazy on how the control works, so if my explanations are a bit hazy, the article I linked probably has a more cogent explanation. :) ) CalendarViewContentPresenter: protected override Size ArrangeOverride(Size finalSize) { int columnCount = this.CalendarView.Periods.Count; Size columnSize = new Size(finalSize.Width / columnCount, finalSize.Height); double elementX = 0; foreach (UIElement element in this.visualChildren) { element.Arrange(new Rect(new Point(elementX, 0), columnSize)); elementX = elementX + columnSize.Width; } return finalSize; } protected override Size MeasureOverride(Size constraint) { this.GenerateVisualChildren(); this.GenerateListViewItemVisuals(); // If it's coming back infinity, just return some value. if (constraint.Width == Double.PositiveInfinity) constraint.Width = 10; if (constraint.Height == Double.PositiveInfinity) constraint.Height = 10; return constraint; } CalendarViewPeriodPersenter: protected override Size ArrangeOverride(Size finalSize) { foreach (UIElement element in this.visualChildren) { element.Arrange(new Rect(new Point(0, 0), finalSize)); } return finalSize; } protected override Size MeasureOverride(Size constraint) { this.GenerateVisualChildren(); return constraint; } RangePanel: protected override Size ArrangeOverride(Size finalSize) { double containerRange = (this.Maximum - this.Minimum); foreach (UIElement element in this.Children) { double begin = (double)element.GetValue(RangePanel.BeginProperty); double end = (double)element.GetValue(RangePanel.EndProperty); double elementRange = end - begin; Size size = new Size(); size.Width = (Orientation == Orientation.Vertical) ? finalSize.Width : elementRange / containerRange * finalSize.Width; size.Height = (Orientation == Orientation.Vertical) ? elementRange / containerRange * finalSize.Height : finalSize.Height; Point location = new Point(); location.X = (Orientation == Orientation.Vertical) ? 0 : (begin - this.Minimum) / containerRange * finalSize.Width; location.Y = (Orientation == Orientation.Vertical) ? (begin - this.Minimum) / containerRange * finalSize.Height : 0; element.Arrange(new Rect(location, size)); } return finalSize; } protected override Size MeasureOverride(Size availableSize) { foreach (UIElement element in this.Children) { element.Measure(availableSize); } // Constrain infinities if (availableSize.Width == double.PositiveInfinity) availableSize.Width = 10; if (availableSize.Height == double.PositiveInfinity) availableSize.Height = 10; return availableSize; }

    Read the article

  • Need themes for the WPF Toolkit controls (espeically DataGrid)

    - by DanM
    I just downloaded the nice themes collection from the Codeplex WPF Themes site. I like the WhisterBlue and BureauBlue themes a lot, but neither contain any styles for the new controls included in the WPF Toolkit (DataGrid, DatePicker, and Calendar). It seems like someone out there must have extended the themes to cover these controls, but I've had no luck finding them. So, if you have any leads, I'd love to hear them. I should also mention that I've been trying to port a Silverlight version of the BureauBlue DataGrid theme to WPF (see: http://stackoverflow.com/questions/1611135/how-do-you-port-a-theme-from-silverlight-to-wpf), but that has been quite unsuccessful so far.

    Read the article

  • WPF Custom Control with Image problem

    - by user311883
    Hi all, I am quite new to WPF/XAML and I am currently facing a problem. I have a solution with two projects in it, the first project is a Custom Control Library with a custom Window form control inside. The second project is a WPF application using my custom window form. All work fine except for the form Icon. In the WPF application project I set my window icon property to "/ProjectTwoNameSpace;component/Resources/Images/Film.ico", and in the WPF custom control I try to show that image that way : <Image Grid.Column="0" Margin="3" Width="27" Height="27"> <Image.Source> <BitmapImage UriSource="{Binding Path=Icon}" /> </Image.Source> </Image> But it doesn't work, I get a error at runtime saying that the property UriSource or StreamSource must be set for my tag. Anyone can help me ? I think it's jsut a WPF newbie problem ^^

    Read the article

  • What is the differnce between DataTemplate and DataContext in WPF?

    - by Ashish Ashu
    I can set the relationship b/w View Model and view through following DataContext syntax: <UserControl.DataContext> <view_model:MainMenuModel /> </UserControl.DataContext> And I can also set the relationship b/w View Model and view through following DataTemplate syntax: <DataTemplate DataType="{x:Type viewModel:UserViewModel}"> <view:UserView /> </DataTemplate> Please let me know what is the difference between the two ? Is the second XAML does not set the data context of a view ?

    Read the article

  • How to explicitly select the row in ListView in WPF?

    - by Ashish Ashu
    I have a ListView in which one of the column contains combo box. I have binded the selectedItem of a Listview, so that I get the current object (selected row ) in the listview. When I do any operation in a combo box like selection change then the listview row ( in which that combo box belongs) is not selected be default and hence my selectedItem gives null or previous row selected object. Please Help!!

    Read the article

  • How to add custom-control-derived TabItem to TabControl in WPF?

    - by orloffm
    I want to have my own base TabItem class and use other classes that derive from it. I define base class in MyNs namespace like this: public class MyCustomTab : TabItem { static MyCustomTab() { DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomTab), new FrameworkPropertyMetadata(typeof(TabItem))); } } And this is what I do for the class that inherits from it: code-behind in MyNs namespace: public partial class ActualTab : MyCustomTab { public ActualTab() { InitializeComponent(); } } XAML: <MyCustomTab x:Class="MyNs.ActualTab" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Grid> </Grid> </MyCustomTab> The error I get is "The tag 'MyCustomTab' does not exist in XML namespace 'http://schemas.microsoft.com/winfx/2006/xaml/presentation'". If I use TabItem tag in XAML the error says that it's not possible to define to different base classes. How to fix this?

    Read the article

  • WPF: How to data bind an object to an element and apply a data template through code?

    - by Boris
    I have created a class LeagueMatch. public class LeagueMatch { public string Home { get { return home; } set { home = value; } } public string Visitor { get { return visitor; } set { visitor = value; } } private string home; private string visitor; public LeagueMatch() { } } Next, I have defined a datatemplate resource for LeagueMatch objects in XAML: <DataTemplate x:Key="MatchTemplate" DataType="{x:Type entities:LeagueMatch}"> <Grid Name="MatchGrid" Width="140" Height="50" Margin="5"> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="*" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <TextBlock Grid.Row="0" Text="{Binding Home}" /> <TextBlock Grid.Row="1" Text="- vs -" /> <TextBlock Grid.Row="2" Text="{Binding Visitor}" /> </Grid> </DataTemplate> In the XAML code-behind, I want to create a ContentPresenter object and to set it's data binding to a previously initialized LeagueMatch object and apply the defined data template. How is that supposed to be done? Thanks.

    Read the article

  • foreach Control ctrl in SomePanel.Controls does not get all controls

    - by aron
    Hello, I have a panel with a bunch of labeles and textboxes inside of it. The code: foreach (Control ctrl in this.pnlSolutions.Controls) Seems to only be finding html table inside the panel and 2 liternals. But it does not get the textboxes that are in the html table. Is there a simple way to get all the controls inside of a panel regardless of the nesting? thanks!

    Read the article

  • ASP.Net validation controls

    - by nikolaosk
    In this post I would like to continue talking about validation in ASP.Net applications. I will look into the validation controls that ASP.Net provides. You can have a look at the first post in my blog regarding validation. You will show you that we can perform all our main validation tasks without almost writing any code. We will add validation to our form by adding one or more controls.We can also display messages to the user. The controls I am going to look into are: CompareValidator CustomValidator...(read more)

    Read the article

  • Programmatically Add Controls to WPF Form

    - by user210757
    I am trying to add controls to a UserControl dynamically (programatically). I get a generic List of objects from my Business Layer (retrieved from the database), and for each object, I want to add a Label, and a TextBox to the WPF UserControl and set the Position and widths to make look nice, and hopefully take advantage of the WPF Validation capabilities. This is something that would be easy in Windows Forms programming but I'm new to WPF. How do I do this (see comments for questions) Say this is my object: public class Field { public string Name { get; set; } public int Length { get; set; } public bool Required { get; set; } } Then in my WPF UserControl, I'm trying to create a Label and TextBox for each object: public void createControls() { List<Field> fields = businessObj.getFields(); Label label = null; TextBox textbox = null; foreach (Field field in fields) { label = new TextBox(); // HOW TO set text, x and y (margin), width, validation based upon object? // i have tried this without luck: // Binding b = new Binding("Name"); // BindingOperations.SetBinding(label, Label.ContentProperty, b); MyGrid.Children.Add(label); textbox = new TextBox(); // ??? MyGrid.Children.Add(textbox); } // databind? this.DataContext = fields; }

    Read the article

  • intercept RelativeSource FindAncestor

    - by Pradeep
    I have a WPF application which runs as a excel plugin, it has its visual tree like so Excel ElementHost WPF UserControl WPF ribbon bar control Now any controls sitting on the WPF ribbon bar control are not enabled when the plugin is loaded within excel. See error below System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Window', AncestorLevel='1''. BindingExpression:Path=IsActive; DataItem=null; target element is 'Ribbon' (Name=''); target property is 'NoTarget' (type 'Object') If I nest the ribbon bar control in a standalone Window(outside excel) it works fine. Is there a way to intercept the FindAncestor call for a Window and wire it to something else.? Note that I cannot change the above binding as it isn't my control.

    Read the article

  • Building applications with WPF, MVVM and Prism(aka CAG)

    - by skjagini
    In this article I am going to walk through an application using WPF and Prism (aka composite application guidance, CAG) which simulates engaging a taxi (cab).  The rules are simple, the app would have3 screens A login screen to authenticate the user An information screen. A screen to engage the cab and roam around and calculating the total fare Metered Rate of Fare The meter is required to be engaged when a cab is occupied by anyone $3.00 upon entry $0.35 for each additional unit The unit fare is: one-fifth of a mile, when the cab is traveling at 6 miles an hour or more; or 60 seconds when not in motion or traveling at less than 12 miles per hour. Night surcharge of $.50 after 8:00 PM & before 6:00 AM Peak hour Weekday Surcharge of $1.00 Monday - Friday after 4:00 PM & before 8:00 PM New York State Tax Surcharge of $.50 per ride. Example: Friday (2010-10-08) 5:30pm Start at Lexington Ave & E 57th St End at Irving Pl & E 15th St Start = $3.00 Travels 2 miles at less than 6 mph for 15 minutes = $3.50 Travels at more than 12 mph for 5 minutes = $1.75 Peak hour Weekday Surcharge = $1.00 (ride started at 5:30 pm) New York State Tax Surcharge = $0.50 Before we dive into the app, I would like to give brief description about the framework.  If you want to jump on to the source code, scroll all the way to the end of the post. MVVM MVVM pattern is in no way related to the usage of PRISM in your application and should be considered if you are using WPF irrespective of PRISM or not. Lets say you are not familiar with MVVM, your typical UI would involve adding some UI controls like text boxes, a button, double clicking on the button,  generating event handler, calling a method from business layer and updating the user interface, it works most of the time for developing small scale applications. The problem with this approach is that there is some amount of code specific to business logic wrapped in UI specific code which is hard to unit test it, mock it and MVVM helps to solve the exact problem. MVVM stands for Model(M) – View(V) – ViewModel(VM),  based on the interactions with in the three parties it should be called VVMM,  MVVM sounds more like MVC (Model-View-Controller) so the name. Why it should be called VVMM: View – View Model - Model WPF allows to create user interfaces using XAML and MVVM takes it to the next level by allowing complete separation of user interface and business logic. In WPF each view will have a property, DataContext when set to an instance of a class (which happens to be your view model) provides the data the view is interested in, i.e., view interacts with view model and at the same time view model interacts with view through DataContext. Sujith, if view and view model are interacting directly with each other how does MVVM is helping me separation of concerns? Well, the catch is DataContext is of type Object, since it is of type object view doesn’t know exact type of view model allowing views and views models to be loosely coupled. View models aggregate data from models (data access layer, services, etc) and make it available for views through properties, methods etc, i.e., View Models interact with Models. PRISM Prism is provided by Microsoft Patterns and Practices team and it can be downloaded from codeplex for source code,  samples and documentation on msdn.  The name composite implies, to compose user interface from different modules (views) without direct dependencies on each other, again allowing  loosely coupled development. Well Sujith, I can already do that with user controls, why shall I learn another framework?  That’s correct, you can decouple using user controls, but you still have to manage some amount of coupling, like how to do you communicate between the controls, how do you subscribe/unsubscribe, loading/unloading views dynamically. Prism is not a replacement for user controls, provides the following features which greatly help in designing the composite applications. Dependency Injection (DI)/ Inversion of Control (IoC) Modules Regions Event Aggregator  Commands Simply put, MVVM helps building a single view and Prism helps building an application using the views There are other open source alternatives to Prism, like MVVMLight, Cinch, take a look at them as well. Lets dig into the source code.  1. Solution The solution is made of the following projects Framework: Holds the common functionality in building applications using WPF and Prism TaxiClient: Start up project, boot strapping and app styling TaxiCommon: Helps with the business logic TaxiModules: Holds the meat of the application with views and view models TaxiTests: To test the application 2. DI / IoC Dependency Injection (DI) as the name implies refers to injecting dependencies and Inversion of Control (IoC) means the calling code has no direct control on the dependencies, opposite of normal way of programming where dependencies are passed by caller, i.e inversion; aside from some differences in terminology the concept is same in both the cases. The idea behind DI/IoC pattern is to reduce the amount of direct coupling between different components of the application, the higher the dependency the more tightly coupled the application resulting in code which is hard to modify, unit test and mock.  Initializing Dependency Injection through BootStrapper TaxiClient is the starting project of the solution and App (App.xaml)  is the starting class that gets called when you run the application. From the App’s OnStartup method we will invoke BootStrapper.   namespace TaxiClient { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e);   (new BootStrapper()).Run(); } } } BootStrapper is your contact point for initializing the application including dependency injection, creating Shell and other frameworks. We are going to use Unity for DI and there are lot of open source DI frameworks like Spring.Net, StructureMap etc with different feature set  and you can choose a framework based on your preferences. Note that Prism comes with in built support for Unity, for example we are deriving from UnityBootStrapper in our case and for any other DI framework you have to extend the Prism appropriately   namespace TaxiClient { public class BootStrapper: UnityBootstrapper { protected override IModuleCatalog CreateModuleCatalog() { return new ConfigurationModuleCatalog(); } protected override DependencyObject CreateShell() { Framework.FrameworkBootStrapper.Run(Container, Application.Current.Dispatcher);   Shell shell = new Shell(); shell.ResizeMode = ResizeMode.NoResize; shell.Show();   return shell; } } } Lets take a look into  FrameworkBootStrapper to check out how to register with unity container. namespace Framework { public class FrameworkBootStrapper { public static void Run(IUnityContainer container, Dispatcher dispatcher) { UIDispatcher uiDispatcher = new UIDispatcher(dispatcher); container.RegisterInstance<IDispatcherService>(uiDispatcher);   container.RegisterType<IInjectSingleViewService, InjectSingleViewService>( new ContainerControlledLifetimeManager());   . . . } } } In the above code we are registering two components with unity container. You shall observe that we are following two different approaches, RegisterInstance and RegisterType.  With RegisterInstance we are registering an existing instance and the same instance will be returned for every request made for IDispatcherService   and with RegisterType we are requesting unity container to create an instance for us when required, i.e., when I request for an instance for IInjectSingleViewService, unity will create/return an instance of InjectSingleViewService class and with RegisterType we can configure the life time of the instance being created. With ContaienrControllerLifetimeManager, the unity container caches the instance and reuses for any subsequent requests, without recreating a new instance. Lets take a look into FareViewModel.cs and it’s constructor. The constructor takes one parameter IEventAggregator and if you try to find all references in your solution for IEventAggregator, you will not find a single location where an instance of EventAggregator is passed directly to the constructor. The compiler still finds an instance and works fine because Prism is already configured when used with Unity container to return an instance of EventAggregator when requested for IEventAggregator and in this particular case it is called constructor injection. public class FareViewModel:ObservableBase, IDataErrorInfo { ... private IEventAggregator _eventAggregator;   public FareViewModel(IEventAggregator eventAggregator) { _eventAggregator = eventAggregator; InitializePropertyNames(); InitializeModel(); PropertyChanged += OnPropertyChanged; } ... 3. Shell Shells are very similar in operation to Master Pages in asp.net or MDI in Windows Forms. And shells contain regions which display the views, you can have as many regions as you wish in a given view. You can also nest regions. i.e, one region can load a view which in itself may contain other regions. We have to create a shell at the start of the application and are doing it by overriding CreateShell method from BootStrapper From the following Shell.xaml you shall notice that we have two content controls with Region names as ‘MenuRegion’ and ‘MainRegion’.  The idea here is that you can inject any user controls into the regions dynamically, i.e., a Menu User Control for MenuRegion and based on the user action you can load appropriate view into MainRegion.    <Window x:Class="TaxiClient.Shell" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Regions="clr-namespace:Microsoft.Practices.Prism.Regions;assembly=Microsoft.Practices.Prism" Title="Taxi" Height="370" Width="800"> <Grid Margin="2"> <ContentControl Regions:RegionManager.RegionName="MenuRegion" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" />   <ContentControl Grid.Row="1" Regions:RegionManager.RegionName="MainRegion" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" /> <!--<Border Grid.ColumnSpan="2" BorderThickness="2" CornerRadius="3" BorderBrush="LightBlue" />-->   </Grid> </Window> 4. Modules Prism provides the ability to build composite applications and modules play an important role in it. For example if you are building a Mortgage Loan Processor application with 3 components, i.e. customer’s credit history,  existing mortgages, new home/loan information; and consider that the customer’s credit history component involves gathering data about his/her address, background information, job details etc. The idea here using Prism modules is to separate the implementation of these 3 components into their own visual studio projects allowing to build components with no dependency on each other and independently. If we need to add another component to the application, the component can be developed by in house team or some other team in the organization by starting with a new Visual Studio project and adding to the solution at the run time with very little knowledge about the application. Prism modules are defined by implementing the IModule interface and each visual studio project to be considered as a module should implement the IModule interface.  From the BootStrapper.cs you shall observe that we are overriding the method by returning a ConfiguratingModuleCatalog which returns the modules that are registered for the application using the app.config file  and you can also add module using code. Lets take a look into configuration file.   <?xml version="1.0"?> <configuration> <configSections> <section name="modules" type="Microsoft.Practices.Prism.Modularity.ModulesConfigurationSection, Microsoft.Practices.Prism"/> </configSections> <modules> <module assemblyFile="TaxiModules.dll" moduleType="TaxiModules.ModuleInitializer, TaxiModules" moduleName="TaxiModules"/> </modules> </configuration> Here we are adding TaxiModules project to our solution and TaxiModules.ModuleInitializer implements IModule interface   5. Module Mapper With Prism modules you can dynamically add or remove modules from the regions, apart from that Prism also provides API to control adding/removing the views from a region within the same module. Taxi Information Screen: Engage the Taxi Screen: The sample application has two screens, ‘Taxi Information’ and ‘Engage the Taxi’ and they both reside in same module, TaxiModules. ‘Engage the Taxi’ is again made of two user controls, FareView on the left and TotalView on the right. We have created a Shell with two regions, MenuRegion and MainRegion with menu loaded into MenuRegion. We can create a wrapper user control called EngageTheTaxi made of FareView and TotalView and load either TaxiInfo or EngageTheTaxi into MainRegion based on the user action. Though it will work it tightly binds the user controls and for every combination of user controls, we need to create a dummy wrapper control to contain them. Instead we can apply the principles we learned so far from Shell/regions and introduce another template (LeftAndRightRegionView.xaml) made of two regions Region1 (left) and Region2 (right) and load  FareView and TotalView dynamically.  To help with loading of the views dynamically I have introduce an helper an interface, IInjectSingleViewService,  idea suggested by Mike Taulty, a must read blog for .Net developers. using System; using System.Collections.Generic; using System.ComponentModel;   namespace Framework.PresentationUtility.Navigation {   public interface IInjectSingleViewService : INotifyPropertyChanged { IEnumerable<CommandViewDefinition> Commands { get; } IEnumerable<ModuleViewDefinition> Modules { get; }   void RegisterViewForRegion(string commandName, string viewName, string regionName, Type viewType); void ClearViewFromRegion(string viewName, string regionName); void RegisterModule(string moduleName, IList<ModuleMapper> moduleMappers); } } The Interface declares three methods to work with views: RegisterViewForRegion: Registers a view with a particular region. You can register multiple views and their regions under one command.  When this particular command is invoked all the views registered under it will be loaded into their regions. ClearViewFromRegion: To unload a specific view from a region. RegisterModule: The idea is when a command is invoked you can load the UI with set of controls in their default position and based on the user interaction, you can load different contols in to different regions on the fly.  And it is supported ModuleViewDefinition and ModuleMappers as shown below. namespace Framework.PresentationUtility.Navigation { public class ModuleViewDefinition { public string ModuleName { get; set; } public IList<ModuleMapper> ModuleMappers; public ICommand Command { get; set; } }   public class ModuleMapper { public string ViewName { get; set; } public string RegionName { get; set; } public Type ViewType { get; set; } } } 6. Event Aggregator Prism event aggregator enables messaging between components as in Observable pattern, Notifier notifies the Observer which receives notification it is interested in. When it comes to Observable pattern, Observer has to unsubscribes for notifications when it no longer interested in notifications, which allows the Notifier to remove the Observer’s reference from it’s local cache. Though .Net has managed garbage collection it cannot remove inactive the instances referenced by an active instance resulting in memory leak, keeping the Observers in memory as long as Notifier stays in memory.  Developers have to be very careful to unsubscribe when necessary and it often gets overlooked, to overcome these problems Prism Event Aggregator uses weak references to cache the reference (Observer in this case)  and releases the reference (memory) once the instance goes out of scope. Using event aggregator is very simple, declare a generic type of CompositePresenationEvent by inheriting from it. using Microsoft.Practices.Prism.Events; using TaxiCommon.BAO;   namespace TaxiCommon.CompositeEvents { public class TaxiOnMoveEvent:CompositePresentationEvent<TaxiOnMove> { } }   TaxiOnMove.cs includes the properties which we want to exchange between the parties, FareView and TotalView. using System;   namespace TaxiCommon.BAO { public class TaxiOnMove { public TimeSpan MinutesAtTweleveMPH { get; set; } public double MilesAtSixMPH { get; set; } } }   Lets take a look into FareViewodel (Notifier) and how it raises the event.  Here we are raising the event by getting the event through GetEvent<..>() and publishing it with the payload private void OnAddMinutes(object obj) { TaxiOnMove payload = new TaxiOnMove(); if(MilesAtSixMPH != null) payload.MilesAtSixMPH = MilesAtSixMPH.Value; if(MinutesAtTweleveMPH != null) payload.MinutesAtTweleveMPH = new TimeSpan(0,0,MinutesAtTweleveMPH.Value,0);   _eventAggregator.GetEvent<TaxiOnMoveEvent>().Publish(payload); ResetMinutesAndMiles(); } And TotalViewModel(Observer) subscribes to notifications by getting the event through GetEvent<..>() namespace TaxiModules.ViewModels { public class TotalViewModel:ObservableBase { .... private IEventAggregator _eventAggregator;   public TotalViewModel(IEventAggregator eventAggregator) { _eventAggregator = eventAggregator; ... }   private void SubscribeToEvents() { _eventAggregator.GetEvent<TaxiStartedEvent>() .Subscribe(OnTaxiStarted, ThreadOption.UIThread,false,(filter) => true); _eventAggregator.GetEvent<TaxiOnMoveEvent>() .Subscribe(OnTaxiMove, ThreadOption.UIThread, false, (filter) => true); _eventAggregator.GetEvent<TaxiResetEvent>() .Subscribe(OnTaxiReset, ThreadOption.UIThread, false, (filter) => true); }   ... private void OnTaxiMove(TaxiOnMove taxiOnMove) { OnMoveFare fare = new OnMoveFare(taxiOnMove); Fares.Add(fare); SetTotalFare(new []{fare}); }   .... 7. MVVM through example In this section we are going to look into MVVM implementation through example.  I have all the modules declared in a single project, TaxiModules, again it is not necessary to have them into one project. Once the user logs into the application, will be greeted with the ‘Engage the Taxi’ screen which is made of two user controls, FareView.xaml and TotalView.Xaml. As you can see from the solution explorer, each of them have their own code behind files and  ViewModel classes, FareViewMode.cs, TotalViewModel.cs Lets take a look in to the FareView and how it interacts with FareViewModel using MVVM implementation. FareView.xaml acts as a view and FareViewMode.cs is it’s view model. The FareView code behind class   namespace TaxiModules.Views { /// <summary> /// Interaction logic for FareView.xaml /// </summary> public partial class FareView : UserControl { public FareView(FareViewModel viewModel) { InitializeComponent(); this.Loaded += (s, e) => { this.DataContext = viewModel; }; } } } The FareView is bound to FareViewModel through the data context  and you shall observe that DataContext is of type Object, i.e. the FareView doesn’t really know the type of ViewModel (FareViewModel). This helps separation of View and ViewModel as View and ViewModel are independent of each other, you can bind FareView to FareViewModel2 as well and the application compiles just fine. Lets take a look into FareView xaml file  <UserControl x:Class="TaxiModules.Views.FareView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Toolkit="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit" xmlns:Commands="clr-namespace:Microsoft.Practices.Prism.Commands;assembly=Microsoft.Practices.Prism"> <Grid Margin="10" > ....   <Border Style="{DynamicResource innerBorder}" Grid.Row="0" Grid.Column="0" Grid.RowSpan="11" Grid.ColumnSpan="2" Panel.ZIndex="1"/>   <Label Grid.Row="0" Content="Engage the Taxi" Style="{DynamicResource innerHeader}"/> <Label Grid.Row="1" Content="Select the State"/> <ComboBox Grid.Row="1" Grid.Column="1" ItemsSource="{Binding States}" Height="auto"> <ComboBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Name}"/> </DataTemplate> </ComboBox.ItemTemplate> <ComboBox.SelectedItem> <Binding Path="SelectedState" Mode="TwoWay"/> </ComboBox.SelectedItem> </ComboBox> <Label Grid.Row="2" Content="Select the Date of Entry"/> <Toolkit:DatePicker Grid.Row="2" Grid.Column="1" SelectedDate="{Binding DateOfEntry, ValidatesOnDataErrors=true}" /> <Label Grid.Row="3" Content="Enter time 24hr format"/> <TextBox Grid.Row="3" Grid.Column="1" Text="{Binding TimeOfEntry, TargetNullValue=''}"/> <Button Grid.Row="4" Grid.Column="1" Content="Start the Meter" Commands:Click.Command="{Binding StartMeterCommand}" />   <Label Grid.Row="5" Content="Run the Taxi" Style="{DynamicResource innerHeader}"/> <Label Grid.Row="6" Content="Number of Miles &lt;@6mph"/> <TextBox Grid.Row="6" Grid.Column="1" Text="{Binding MilesAtSixMPH, TargetNullValue='', ValidatesOnDataErrors=true}"/> <Label Grid.Row="7" Content="Number of Minutes @12mph"/> <TextBox Grid.Row="7" Grid.Column="1" Text="{Binding MinutesAtTweleveMPH, TargetNullValue=''}"/> <Button Grid.Row="8" Grid.Column="1" Content="Add Minutes and Miles " Commands:Click.Command="{Binding AddMinutesCommand}"/> <Label Grid.Row="9" Content="Other Operations" Style="{DynamicResource innerHeader}"/> <Button Grid.Row="10" Grid.Column="1" Content="Reset the Meter" Commands:Click.Command="{Binding ResetCommand}"/>   </Grid> </UserControl> The highlighted code from the above code shows data binding, for example ComboBox which displays list of states has it’s ItemsSource bound to States property, with DataTemplate bound to Name and SelectedItem  to SelectedState. You might be wondering what are all these properties and how it is able to bind to them.  The answer lies in data context, i.e., when you bound a control, WPF looks for data context on the root object (Grid in this case) and if it can’t find data context it will look into root’s root, i.e. FareView UserControl and it is bound to FareViewModel.  Each of those properties have be declared on the ViewModel for the View to bind correctly. To put simply, View is bound to ViewModel through data context of type object and every control that is bound on the View actually binds to the public property on the ViewModel. Lets look into the ViewModel code (the following code is not an exact copy of FareViewMode.cs, pasted relevant code for this section)   namespace TaxiModules.ViewModels { public class FareViewModel:ObservableBase, IDataErrorInfo { public List<USState> States { get { return USStates.StateList; } }   public USState SelectedState { get { return _selectedState; } set { _selectedState = value; RaisePropertyChanged(_selectedStatePropertyName); } }   public DateTime? DateOfEntry { get { return _dateOfEntry; } set { _dateOfEntry = value; RaisePropertyChanged(_dateOfEntryPropertyName); } }   public TimeSpan? TimeOfEntry { get { return _timeOfEntry; } set { _timeOfEntry = value; RaisePropertyChanged(_timeOfEntryPropertyName); } }   public double? MilesAtSixMPH { get { return _milesAtSixMPH; } set { _milesAtSixMPH = value; RaisePropertyChanged(_distanceAtSixMPHPropertyName); } }   public int? MinutesAtTweleveMPH { get { return _minutesAtTweleveMPH; } set { _minutesAtTweleveMPH = value; RaisePropertyChanged(_minutesAtTweleveMPHPropertyName); } }   public ICommand StartMeterCommand { get { if(_startMeterCommand == null) { _startMeterCommand = new DelegateCommand<object>(OnStartMeter, CanStartMeter); } return _startMeterCommand; } }   public ICommand AddMinutesCommand { get { if(_addMinutesCommand == null) { _addMinutesCommand = new DelegateCommand<object>(OnAddMinutes, CanAddMinutes); } return _addMinutesCommand; } }   public ICommand ResetCommand { get { if(_resetCommand == null) { _resetCommand = new DelegateCommand<object>(OnResetCommand); } return _resetCommand; } }   } private void OnStartMeter(object obj) { _eventAggregator.GetEvent<TaxiStartedEvent>().Publish( new TaxiStarted() { EngagedOn = DateOfEntry.Value.Date + TimeOfEntry.Value, EngagedState = SelectedState.Value });   _isMeterStarted = true; OnPropertyChanged(this,null); } And views communicate user actions like button clicks, tree view item selections, etc using commands. When user clicks on ‘Start the Meter’ button it invokes the method StartMeterCommand, which calls the method OnStartMeter which publishes the event to TotalViewModel using event aggregator  and TaxiStartedEvent. namespace TaxiModules.ViewModels { public class TotalViewModel:ObservableBase { ... private IEventAggregator _eventAggregator;   public TotalViewModel(IEventAggregator eventAggregator) { _eventAggregator = eventAggregator;   InitializePropertyNames(); InitializeModel(); SubscribeToEvents(); }   public decimal? TotalFare { get { return _totalFare; } set { _totalFare = value; RaisePropertyChanged(_totalFarePropertyName); } } .... private void SubscribeToEvents() { _eventAggregator.GetEvent<TaxiStartedEvent>().Subscribe(OnTaxiStarted, ThreadOption.UIThread,false,(filter) => true); _eventAggregator.GetEvent<TaxiOnMoveEvent>().Subscribe(OnTaxiMove, ThreadOption.UIThread, false, (filter) => true); _eventAggregator.GetEvent<TaxiResetEvent>().Subscribe(OnTaxiReset, ThreadOption.UIThread, false, (filter) => true); }   private void OnTaxiStarted(TaxiStarted taxiStarted) { Fares.Add(new EntryFare()); Fares.Add(new StateTaxFare(taxiStarted)); Fares.Add(new NightSurchargeFare(taxiStarted)); Fares.Add(new PeakHourWeekdayFare(taxiStarted));   SetTotalFare(Fares); }   private void SetTotalFare(IEnumerable<IFare> fares) { TotalFare = (_totalFare ?? 0) + TaxiFareHelper.GetTotalFare(fares); } ....   } }   TotalViewModel subscribes to events, TaxiStartedEvent and rest. When TaxiStartedEvent gets invoked it calls the OnTaxiStarted method which sets the total fare which includes entry fee, state tax, nightly surcharge, peak hour weekday fare.   Note that TotalViewModel derives from ObservableBase which implements the method RaisePropertyChanged which we are invoking in Set of TotalFare property, i.e, once we update the TotalFare property it raises an the event that  allows the TotalFare text box to fetch the new value through the data context. ViewModel is communicating with View through data context and it has no knowledge about View, helping in loose coupling of ViewModel and View.   I have attached the source code (.Net 4.0, Prism 4.0, VS 2010) , download and play with it and don’t forget to leave your comments.  

    Read the article

  • UserAppDataPath in WPF

    - by psheriff
    In Windows Forms applications you were able to get to your user's roaming profile directory very easily using the Application.UserAppDataPath property. This folder allows you to store information for your program in a custom folder specifically for your program. The format of this directory looks like this: C:\Users\YOUR NAME\AppData\Roaming\COMPANY NAME\APPLICATION NAME\APPLICATION VERSION For example, on my Windows 7 64-bit system, this folder would look like this for a Windows Forms Application: C:\Users\PSheriff\AppData\Roaming\PDSA, Inc.\WindowsFormsApplication1\1.0.0.0 For some reason Microsoft did not expose this property from the Application object of WPF applications. I guess they think that we don't need this property in WPF? Well, sometimes we still do need to get at this folder. You have two choices on how to retrieve this property. Add a reference to the System.Windows.Forms.dll to your WPF application and use this property directly. Or, you can write your own method to build the same path. If you add a reference to the System.Windows.Forms.dll you will need to use System.Windows.Forms.Application.UserAppDataPath to access this property. Create a GetUserAppDataPath Method in WPF If you want to build this path you can do so with just a few method calls in WPF using Reflection. The code below shows this fairly simple method to retrieve the same folder as shown above. C#using System.Reflection; public string GetUserAppDataPath(){  string path = string.Empty;  Assembly assm;  Type at;  object[] r;   // Get the .EXE assembly  assm = Assembly.GetEntryAssembly();  // Get a 'Type' of the AssemblyCompanyAttribute  at = typeof(AssemblyCompanyAttribute);  // Get a collection of custom attributes from the .EXE assembly  r = assm.GetCustomAttributes(at, false);  // Get the Company Attribute  AssemblyCompanyAttribute ct =                 ((AssemblyCompanyAttribute)(r[0]));  // Build the User App Data Path  path = Environment.GetFolderPath(              Environment.SpecialFolder.ApplicationData);  path += @"\" + ct.Company;  path += @"\" + assm.GetName().Version.ToString();   return path;} Visual BasicPublic Function GetUserAppDataPath() As String  Dim path As String = String.Empty  Dim assm As Assembly  Dim at As Type  Dim r As Object()   ' Get the .EXE assembly  assm = Assembly.GetEntryAssembly()  ' Get a 'Type' of the AssemblyCompanyAttribute  at = GetType(AssemblyCompanyAttribute)  ' Get a collection of custom attributes from the .EXE assembly  r = assm.GetCustomAttributes(at, False)  ' Get the Company Attribute  Dim ct As AssemblyCompanyAttribute = _                 DirectCast(r(0), AssemblyCompanyAttribute)  ' Build the User App Data Path  path = Environment.GetFolderPath( _                 Environment.SpecialFolder.ApplicationData)  path &= "\" & ct.Company  path &= "\" & assm.GetName().Version.ToString()   Return pathEnd Function Summary Getting the User Application Data Path folder in WPF is fairly simple with just a few method calls using Reflection. Of course, there is absolutely no reason you cannot just add a reference to the System.Windows.Forms.dll to your WPF application and use that Application object. After all, System.Windows.Forms.dll is a part of the .NET Framework and can be used from WPF with no issues at all. NOTE: Visit http://www.pdsa.com/downloads to get more tips and tricks like this one. Good Luck with your Coding,Paul Sheriff ** SPECIAL OFFER FOR MY BLOG READERS **We frequently offer a FREE gift for readers of my blog. Visit http://www.pdsa.com/Event/Blog for your FREE gift!

    Read the article

  • WPF more dynamic views and DataAnnotations

    - by Ingó Vals
    Comparing WPF and Asp.Net Razor/HtmlHelper I find WPF/Xaml to be somewhat lacking in creating views. With HtmlHelpers you could define in one place how you wan't to represent specific type of data and include elements set from the DataAnnotations of the property. In WPF you can also define DataTemplates for data but it seems much more limited then EditorTemplates. It doesn't use information from DataAnnotations. Also the layout of elements can be bothersome. I hate having to constantly add RowDefinitions and update the Grid.Row attribute of lot of elements when I add a new property somewhere in line. I understand that GUI programming can be a lot of grunt work like this but as Asp.Net MVC has shown there are ways around that. What solutions are out there to make view creation in WPF a little bit cleaner, maintainable and more dynamic?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >