Search Results

Search found 7209 results on 289 pages for 'wpf triggers'.

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

  • Adding WPF Text Writer Trace Listener in an Outlook Add In using wpf window/control

    - by Deepak N
    I'm working on a outlook 2003 AddIn using VSTO SE.We have few customized windows developed in WPF. It looks there are few client machines have problem with WPF rendering due to which there could be an exception due to addin is getting disabled. I added a outlook.exe.config and added trace listeners for wpf Trace sources. I set it up according this link. The console trace listener is working fine for me. But I'm not able get the TextWriterTraceListener working with config <add name="textListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="Trace.log" /> I tried giving absolute path for trace log file as "C:\Trace.log".The TextWriterTraceListener worked for a dummy wpf app with the same config. Am I missing anything here.

    Read the article

  • WPF Style Triggers: can I apply the one style for a variety of Properties?

    - by Matt H.
    It seems like there has to be a way to do this: I am applying an ItemContainerStyle in my Listbox, based on two property triggers. As you can see, I'm using the exact same set of trigger enter/exit actions, simply applied on two different properties. Is there something equivalent to a <Trigger Property="prop1" OR Property="prop2" ??? (Obviously wouldn't look like that, but that probably gets the point across.) <Style x:Key="ListBoxItemStyle" TargetType="ListBoxItem"> <Style.Triggers> <Trigger Property="IsKeyboardFocusWithin" Value="True"> <Trigger.EnterActions> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty="Height" To="50" Duration="0:0:.3"></DoubleAnimation> </Storyboard> </BeginStoryboard> </Trigger.EnterActions> <Trigger.ExitActions> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty="Height" To="25" Duration="0:0:.3" /> </Storyboard> </BeginStoryboard> </Trigger.ExitActions> </Trigger> </Style.Triggers> </Style> <Style x:Key="ListBoxItemStyle" TargetType="ListBoxItem"> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Trigger.EnterActions> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty="Height" To="50" Duration="0:0:.3"></DoubleAnimation> </Storyboard> </BeginStoryboard> </Trigger.EnterActions> <Trigger.ExitActions> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty="Height" To="25" Duration="0:0:.3" /> </Storyboard> </BeginStoryboard> </Trigger.ExitActions> </Trigger> </Style.Triggers> </Style>

    Read the article

  • Getting Started with Prism (aka Composite Application Guidance for WPF and Silverlight)

    - by dotneteer
    Overview Prism is a framework from the Microsoft Patterns and Practice team that allow you to create WPF and Silverlight in a modular way. It is especially valuable for larger projects in which a large number of developers can develop in parallel. Prism achieves its goal by supplying several services: · Dependency Injection (DI) and Inversion of control (IoC): By using DI, Prism takes away the responsibility of instantiating and managing the life time of dependency objects from individual components to a container. Prism relies on containers to discover, manage and compose large number of objects. By varying the configuration, the container can also inject mock objects for unit testing. Out of the box, Prism supports Unity and MEF as container although it is possible to use other containers by subclassing the Bootstrapper class. · Modularity and Region: Prism supplies the framework to split application into modules from the application shell. Each module is a library project that contains both UI and code and is responsible to initialize itself when loaded by the shell. Each window can be further divided into regions. A region is a user control with associated model. · Model, view and view-model (MVVM) pattern: Prism promotes the user MVVM. The use of DI container makes it much easier to inject model into view. WPF already has excellent data binding and commanding mechanism. To be productive with Prism, it is important to understand WPF data binding and commanding well. · Event-aggregation: Prism promotes loosely coupled components. Prism discourages for components from different modules to communicate each other, thus leading to dependency. Instead, Prism supplies an event-aggregation mechanism that allows components to publish and subscribe events without knowing each other. Architecture In the following, I will go into a little more detail on the services provided by Prism. Bootstrapper In a typical WPF application, application start-up is controls by App.xaml and its code behind. The main window of the application is typically specified in the App.xaml file. In a Prism application, we start a bootstrapper in the App class and delegate the duty of main window to the bootstrapper. The bootstrapper will start a dependency-injection container so all future object instantiations are managed by the container. Out of box, Prism provides the UnityBootstrapper and MefUnityBootstrapper abstract classes. All application needs to either provide a concrete implementation of one of these bootstrappers, or alternatively, subclass the Bootstrapper class with another DI container. A concrete bootstrapper class must implement the CreateShell method. Its responsibility is to resolve and create the Shell object through the DI container to serve as the main window for the application. The other important method to override is ConfigureModuleCatalog. The bootstrapper can register modules for the application. In a more advance scenario, an application does not have to know all its modules at compile time. Modules can be discovered at run time. Readers to refer to one of the Open Modularity Quick Starts for more information. Modules Once modules are registered with or discovered by Prism, they are instantiated by the DI container and their Initialize method is called. The DI container can inject into a module a region registry that implements IRegionViewRegistry interface. The module, in its Initialize method, can then call RegisterViewWithRegion method of the registry to register its regions. Regions Regions, once registered, are managed by the RegionManager. The shell can then load regions either through the RegionManager.RegionName attached property or dynamically through code. When a view is created by the region manager, the DI container can inject view model and other services into the view. The view then has a reference to the view model through which it can interact with backend services. Service locator Although it is possible to inject services into dependent classes through a DI container, an alternative way is to use the ServiceLocator to retrieve a service on demard. Prism supplies a service locator implementation and it is possible to get an instance of the service by calling: ServiceLocator.Current.GetInstance<IServiceType>() Event aggregator Prism supplies an IEventAggregator interface and implementation that can be injected into any class that needs to communicate with each other in a loosely-coupled fashion. The event aggregator uses a publisher/subscriber model. A class can publishes an event by calling eventAggregator.GetEvent<EventType>().Publish(parameter) to raise an event. Other classes can subscribe the event by calling eventAggregator.GetEvent<EventType>().Subscribe(EventHandler, other options). Getting started The easiest way to get started with Prism is to go through the Prism Hands-On labs and look at the Hello World QuickStart. The Hello World QuickStart shows how bootstrapper, modules and region works. Next, I would recommend you to look at the Stock Trader Reference Implementation. It is a more in depth example that resemble we want to set up an application. Several other QuickStarts cover individual Prism services. Some scenarios, such as dynamic module discovery, are more advanced. Apart from the official prism document, you can get an overview by reading Glen Block’s MSDN Magazine article. I have found the best free training material is from the Boise Code Camp. To be effective with Prism, it is important to understands key concepts of WPF well first, such as the DependencyProperty system, data binding, resource, theme and ICommand. It is also important to know your DI container of choice well. I will try to explorer these subjects in depth in the future. Testimony Recently, I worked on a desktop WPF application using Prism. I had a wonderful experience with Prism. The Prism is flexible enough even in the presence of third party controls such as Telerik WPF controls. We have never encountered any significant obstacle.

    Read the article

  • WPF custom BalloonTips problem with multithreading

    - by Erika
    Hi, I have read other related question but i cant really get them to relate to this so I thought it were best to ask, Im pretty new to WPF and so on so please bear with me. I am using this http://www.codeproject.com/KB/WPF/wpf_notifyicon.aspx api to work with custom WPF Windows (in particular FancyBalloon). However, i'm coming across the following problem, I seem unable to start off BalloonTips in a separate thread ( i need this because i'm parsing emails and hence if there are 3 emails for instance, it displays the first email (that works fine), but when it comes to the second email it crashes with a TargetInvocationException , {"Specified element is already the logical child of another element. Disconnect it first."}. Thing is, im supposedly working with the same instance and i have attempted calling it to close it before, disposing it etc but to no avail. (then again if i dispose it, i cant create another instance as apparently WPF UI components must be called from a static thread so throughout the looping of emails + displaying balloon, i am trying to use the same BalloonTip. Any suggestions please? I am really at a loss here and i've been on it for quite a while now :/ I was wondering if there was anyone

    Read the article

  • Wpf vs WinForms for a vb programmer? [closed]

    - by Jeroen
    I am asked by a client to develop an application that is basically a screen on which the user can choose several items to pass the time (used in holding cells in mental hospitals for example). The baisc idea is as follows: TV (choosing this will provide the user with a number of TV streams from the interweb) Radio (...) Games (serveral flash games, also from the interweb) Music (play local music or streams) Draw something (not the game) Create an email Choose lighting settings for the room etc. etc. I am torn between WinForms and WPF for this project. It seems that WPF is the way to go since there is quite a bit of rich media involved but I have a 15 year VB background. The project obviously has a dead line and certain budget that I cannot cross and if I can avoid starting from scratch with some thing that will be nice. Is WPF worth it in this particular case or can I use WinForms with the incorperation of WPF controls? I would very much like to hear your thoughts/comments/suggestions!

    Read the article

  • A WPF Image Button

    - by psheriff
    Instead of a normal button with words, sometimes you want a button that is just graphical. Yes, you can put an Image control in the Content of a normal Button control, but you still have the button outline, and trying to change the style can be rather difficult. Instead I like creating a user control that simulates a button, but just accepts an image. Figure 1 shows an example of three of these custom user controls to represent minimize, maximize and close buttons for a borderless window. Notice the highlighted image button has a gray rectangle around it. You will learn how to highlight using the VisualStateManager in this blog post.Figure 1: Creating a custom user control for things like image buttons gives you complete control over the look and feel.I would suggest you read my previous blog post on creating a custom Button user control as that is a good primer for what I am going to expand upon in this blog post. You can find this blog post at http://weblogs.asp.net/psheriff/archive/2012/08/10/create-your-own-wpf-button-user-controls.aspx.The User ControlThe XAML for this image button user control contains just a few controls, plus a Visual State Manager. The basic outline of the user control is shown below:<Border Grid.Row="0"        Name="borMain"        Style="{StaticResource pdsaButtonImageBorderStyle}"        MouseEnter="borMain_MouseEnter"        MouseLeave="borMain_MouseLeave"        MouseLeftButtonDown="borMain_MouseLeftButtonDown">  <VisualStateManager.VisualStateGroups>  ... MORE XAML HERE ...  </VisualStateManager.VisualStateGroups>  <Image Style="{StaticResource pdsaButtonImageImageStyle}"         Visibility="{Binding Path=Visibility}"         Source="{Binding Path=ImageUri}"         ToolTip="{Binding Path=ToolTip}" /></Border>There is a Border control named borMain and a single Image control in this user control. That is all that is needed to display the buttons shown in Figure 1. The definition for this user control is in a DLL named PDSA.WPF. The Style definitions for both the Border and the Image controls are contained in a resource dictionary names PDSAButtonStyles.xaml. Using a resource dictionary allows you to create a few different resource dictionaries, each with a different theme for the buttons.The Visual State ManagerTo display the highlight around the button as your mouse moves over the control, you will need to add a Visual State Manager group. Two different states are needed; MouseEnter and MouseLeave. In the MouseEnter you create a ColorAnimation to modify the BorderBrush color of the Border control. You specify the color to animate as “DarkGray”. You set the duration to less than a second. The TargetName of this storyboard is the name of the Border control “borMain” and since we are specifying a single color, you need to set the TargetProperty to “BorderBrush.Color”. You do not need any storyboard for the MouseLeave state. Leaving this VisualState empty tells the Visual State Manager to put everything back the way it was before the MouseEnter event.<VisualStateManager.VisualStateGroups>  <VisualStateGroup Name="MouseStates">    <VisualState Name="MouseEnter">      <Storyboard>        <ColorAnimation             To="DarkGray"            Duration="0:0:00.1"            Storyboard.TargetName="borMain"            Storyboard.TargetProperty="BorderBrush.Color" />      </Storyboard>    </VisualState>    <VisualState Name="MouseLeave" />  </VisualStateGroup></VisualStateManager.VisualStateGroups>Writing the Mouse EventsTo trigger the Visual State Manager to run its storyboard in response to the specified event, you need to respond to the MouseEnter event on the Border control. In the code behind for this event call the GoToElementState() method of the VisualStateManager class exposed by the user control. To this method you will pass in the target element (“borMain”) and the state (“MouseEnter”). The VisualStateManager will then run the storyboard contained within the defined state in the XAML.private void borMain_MouseEnter(object sender,  MouseEventArgs e){  VisualStateManager.GoToElementState(borMain,    "MouseEnter", true);}You also need to respond to the MouseLeave event. In this event you call the VisualStateManager as well, but specify “MouseLeave” as the state to go to.private void borMain_MouseLeave(object sender, MouseEventArgs e){  VisualStateManager.GoToElementState(borMain,     "MouseLeave", true);}The Resource DictionaryBelow is the definition of the PDSAButtonStyles.xaml resource dictionary file contained in the PDSA.WPF DLL. This dictionary can be used as the default look and feel for any image button control you add to a window. <ResourceDictionary  ... >  <!-- ************************* -->  <!-- ** Image Button Styles ** -->  <!-- ************************* -->  <!-- Image/Text Button Border -->  <Style TargetType="Border"         x:Key="pdsaButtonImageBorderStyle">    <Setter Property="Margin"            Value="4" />    <Setter Property="Padding"            Value="2" />    <Setter Property="BorderBrush"            Value="Transparent" />    <Setter Property="BorderThickness"            Value="1" />    <Setter Property="VerticalAlignment"            Value="Top" />    <Setter Property="HorizontalAlignment"            Value="Left" />    <Setter Property="Background"            Value="Transparent" />  </Style>  <!-- Image Button -->  <Style TargetType="Image"         x:Key="pdsaButtonImageImageStyle">    <Setter Property="Width"            Value="40" />    <Setter Property="Margin"            Value="6" />    <Setter Property="VerticalAlignment"            Value="Top" />    <Setter Property="HorizontalAlignment"            Value="Left" />  </Style></ResourceDictionary>Using the Button ControlOnce you make a reference to the PDSA.WPF DLL from your WPF application you will see the “PDSAucButtonImage” control appear in your Toolbox. Drag and drop the button onto a Window or User Control in your application. I have not referenced the PDSAButtonStyles.xaml file within the control itself so you do need to add a reference to this resource dictionary somewhere in your application such as in the App.xaml.<Application.Resources>  <ResourceDictionary>    <ResourceDictionary.MergedDictionaries>      <ResourceDictionary         Source="/PDSA.WPF;component/PDSAButtonStyles.xaml" />    </ResourceDictionary.MergedDictionaries>  </ResourceDictionary></Application.Resources>This will give your buttons a default look and feel unless you override that dictionary on a specific Window or User Control or on an individual button. After you have given a global style to your application and you drag your image button onto a window, the following will appear in your XAML window.<my:PDSAucButtonImage ... />There will be some other attributes set on the above XAML, but you simply need to set the x:Name, the ToolTip and ImageUri properties. You will also want to respond to the Click event procedure in order to associate an action with clicking on this button. In the sample code you download for this blog post you will find the declaration of the Minimize button to be the following:<my:PDSAucButtonImage       x:Name="btnMinimize"       Click="btnMinimize_Click"       ToolTip="Minimize Application"       ImageUri="/PDSA.WPF;component/Images/Minus.png" />The ImageUri property is a dependency property in the PDSAucButtonImage user control. The x:Name and the ToolTip we get for free. You have to create the Click event procedure yourself. This is also created in the PDSAucButtonImage user control as follows:private void borMain_MouseLeftButtonDown(object sender,  MouseButtonEventArgs e){  RaiseClick(e);}public delegate void ClickEventHandler(object sender,  RoutedEventArgs e);public event ClickEventHandler Click;protected void RaiseClick(RoutedEventArgs e){  if (null != Click)    Click(this, e);}Since a Border control does not have a Click event you will create one by using the MouseLeftButtonDown on the border to fire an event you create called “Click”.SummaryCreating your own image button control can be done in a variety of ways. In this blog post I showed you how to create a custom user control and simulate a button using a Border and Image control. With just a little bit of code to respond to the MouseLeftButtonDown event on the border you can raise your own Click event. Dependency properties, such as ImageUri, allow you to set attributes on your custom user control. Feel free to expand on this button by adding additional dependency properties, change the resource dictionary, and even the animation to make this button look and act like you want.NOTE: You can download the sample code for this article by visiting my website at http://www.pdsa.com/downloads. Select “Tips & Tricks”, then select “A WPF Image  Button” from the drop down list.

    Read the article

  • .NET WPF Charting Control

    - by Randy Minder
    We're very close to wrapping up a WPF dashboarding application using SSRS (.RDLC files) and the Microsoft Report Viewer. For a number of reasons, this combination has turned out to be less than what we had hoped. One of the biggest problems is that the Microsoft Report Viewer is not a WPF control. We've had other problems as well. Our app consists of at least 5 tabs and each tab has at least 4-5 charts on it. All the charts update on their own timed schedules (like every 15-30 minutes). For the next version I'd like to explore other .NET charting tools for WPF. Performance is absolutely critical. As is resource usage. The tool must support WPF and as many chart types as possible. Can anyone recommend (or not recommend) charting tools they have experience with? We own Telerik and I've dabbled with their charting control. At the 30K foot level, it seems quite nice.

    Read the article

  • WPF Binding to DataRow Columns

    - by Trindaz
    Hi, I've taken some sample code from http://sweux.com/blogs/smoura/index.php/wpf/2009/06/15/wpf-toolkit-datagrid-part-iv-templatecolumns-and-row-grouping/ that provides grouping of data in a WPF DataGrid. I'm modifying the example to use a DataTable instead of a Collection of entities. My problem is in translating a binding declaration {Binding Parent.IsExpanded}, which works fine where Parent is a reference to an entity that has the IsExpanded attribute, to something that will work for my weakly typed DataTable, where Parent is the name of a column and references another DataRow in the same DataTable. I've tried declarations like {Binding Parent.Items[IsExpanded]} and {Binding Parent("IsExpanded")} but none of these seem to work. How can I create a binding to the IsExpanded column of the DataRow Parent in my DataTable? Thanks in advance, Dave

    Read the article

  • WPF DataGrid issue with db40

    - by Rich Blumer
    I am using the following code to populate a wpf datagrid with items in my db4o OODB: IObjectContainer db = Db4oEmbedded.OpenFile(Db4oEmbedded.NewConfiguration(), "C:\Dev\ContractKeeper\Database\ContractKeeper.yap"); var contractTypes = db.Query(typeof(ContractType)); this.dataGrid1.ItemsSource = contractTypes.ToList(); Here is the XAML: <Window x:Class="ContractKeeper.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:dg="http://schemas.microsoft.com/wpf/2008/toolkit" Title="Window1" Height="300" Width="300"> <Grid> <dg:DataGrid AutoGenerateColumns="True" Margin="12,102,12,24" Name="dataGrid1" /> </Grid> </Window> When the items get bound to the datagrid, the gridlines appear like there are records but no data is displayed. Has anyone had this issue with db4o and the wpf datagrid?

    Read the article

  • User Control inherit from ListBox in Wpf?

    - by Rev
    Hi. I want to make a user Control in WPf with same properties and events like ListBox.(can add items , remove them , selecting ,...) on way in windows App is use a user control which is inherit form ListBox. but in WPF I don't know how make User Control inherit from ListBox (or other WPF Control)!!! I write this code but it had an exception public partial class InboxListItem : ListBox { public InboxListItem() { InitializeComponent(); } and It's Xaml file <UserControl x:Class="ListBoxControl.InboxListItem" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:myTypes="clr-namespace:ListBoxControl" />

    Read the article

  • What is Silverlight's relationship -- if any -- to WPF?

    - by xarzu
    I was working with a WPF application and I decided that the controls and graphics I wanted to display on the grid might look better if it was a silverlight component. I thought this way because of all the cool silverlight controls that look very flash-like. But now that I have gottem my Visual Studio 2010 set up with SIlverlight, it seems that every silverlight app I can make are ASP.NET in nature. It seems that instead of a cool GUI control to make, Silverlight is telling me that it is primarely a dataflow sort of application for the web. What is the relationship, if any, between WPF and Silverlight. Can I or can I not put a silverlight control into my existing WPF application?

    Read the article

  • data validation on wpf passwordbox:type password, re-type password

    - by black sensei
    Hello Experts !! I've built a wpf windows application in with there is a registration form. Using IDataErrorInfo i could successfully bind the field to a class property and with the help of styles display meaningful information about the error to users.About the submit button i use the MultiDataTrigger with conditions (Based on a post here on stackoverflow).All went well. Now i need to do the same for the passwordbox and apparently it's not as straight forward.I found on wpftutorial an article and gave it a try but for some reason it wasn't working. i've tried another one from functionalfun. And in this Functionalfun case the properties(databind,databound) are not recognized as dependencyproperty even after i've changed their name as suggested somewhere in the comments plus i don't have an idea whether it will work for a windows application, since it's designed for web. to give you an idea here is some code on textboxes <Window.Resources> <data:General x:Key="recharge" /> <Style x:Key="validButton" TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}" > <Setter Property="IsEnabled" Value="False"/> <Style.Triggers> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding ElementName=txtRecharge, Path=(Validation.HasError)}" Value="false" /> </MultiDataTrigger.Conditions> <Setter Property="IsEnabled" Value="True" /> </MultiDataTrigger> </Style.Triggers> </Style> <Style x:Key="txtboxerrors" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}"> <Style.Triggers> <Trigger Property="Validation.HasError" Value="true"> <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/> <Setter Property="Validation.ErrorTemplate"> <Setter.Value> <ControlTemplate> <DockPanel LastChildFill="True"> <TextBlock DockPanel.Dock="Bottom" FontSize="8" FontWeight="ExtraBold" Foreground="red" Padding="5 0 0 0" Text="{Binding ElementName=showerror, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"></TextBlock> <Border BorderBrush="Red" BorderThickness="2"> <AdornedElementPlaceholder Name="showerror" /> </Border> </DockPanel> </ControlTemplate> </Setter.Value> </Setter> </Trigger> </Style.Triggers> </Style> </Window.Resources> <TextBox Margin="12,69,12,70" Name="txtRecharge" Style="{StaticResource txtboxerrors}"> <TextBox.Text> <Binding Path="Field" Source="{StaticResource recharge}" ValidatesOnDataErrors="True" UpdateSourceTrigger="PropertyChanged"> <Binding.ValidationRules> <ExceptionValidationRule /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> <Button Height="23" Margin="98,0,0,12" Name="btnRecharge" VerticalAlignment="Bottom" Click="btnRecharge_Click" HorizontalAlignment="Left" Width="75" Style="{StaticResource validButton}">Recharge</Button> some C# : class General : IDataErrorInfo { private string _field; public string this[string columnName] { get { string result = null; if(columnName == "Field") { if(Util.NullOrEmtpyCheck(this._field)) { result = "Field cannot be Empty"; } } return result; } } public string Error { get { return null; } } public string Field { get { return _field; } set { _field = value; } } } So what are suggestion you guys have for me? I mean how would you go about this? how do you do this since the databinding first purpose here is not to load data onto the fields they are just (for now) for data validation. thanks for reading this.

    Read the article

  • MEF CompositionInitializer for WPF

    - by Reed
    The Managed Extensibility Framework is an amazingly useful addition to the .NET Framework.  I was very excited to see System.ComponentModel.Composition added to the core framework.  Personally, I feel that MEF is one tool I’ve always been missing in my .NET development. Unfortunately, one perfect scenario for MEF tends to fall short of it’s full potential is in Windows Presentation Foundation development.  In particular, there are many times when the XAML parser constructs objects in WPF development, which makes composition of those parts difficult.  The current release of MEF (Preview Release 9) addresses this for Silverlight developers via System.ComponentModel.Composition.CompositionInitializer.  However, there is no equivalent class for WPF developers. The CompositionInitializer class provides the means for an object to compose itself.  This is very useful with WPF and Silverlight development, since it allows a View, such as a UserControl, to be generated via the standard XAML parser, and still automatically pull in the appropriate ViewModel in an extensible manner.  Glenn Block has demonstrated the usage for Silverlight in detail, but the same issues apply in WPF. As an example, let’s take a look at a very simple case.  Take the following XAML for a Window: <Window x:Class="WpfApplication1.MainView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="220" Width="300"> <Grid> <TextBlock Text="{Binding TheText}" /> </Grid> </Window> This does nothing but create a Window, add a simple TextBlock control, and use it to display the value of our “TheText” property in our DataContext class.  Since this is our main window, WPF will automatically construct and display this Window, so we need to handle constructing the DataContext and setting it ourselves. We could do this in code or in XAML, but in order to do it directly, we would need to hard code the ViewModel type directly into our XAML code, or we would need to construct the ViewModel class and set it in the code behind.  Both have disadvantages, and the disadvantages grow if we’re using MEF to compose our ViewModel. Ideally, we’d like to be able to have MEF construct our ViewModel for us.  This way, it can provide any construction requirements for our ViewModel via [ImportingConstructor], and it can handle fully composing the imported properties on our ViewModel.  CompositionInitializer allows this to occur. We use CompositionInitializer within our View’s constructor, and use it for self-composition of our View.  Using CompositionInitializer, we can modify our code behind to: public partial class MainView : Window { public MainView() { InitializeComponent(); CompositionInitializer.SatisfyImports(this); } [Import("MainViewModel")] public object ViewModel { get { return this.DataContext; } set { this.DataContext = value; } } } We then can add an Export on our ViewModel class like so: [Export("MainViewModel")] public class MainViewModel { public string TheText { get { return "Hello World!"; } } } MEF will automatically compose our application, decoupling our ViewModel injection to the DataContext of our View until runtime.  When we run this, we’ll see: There are many other approaches for using MEF to wire up the extensible parts within your application, of course.  However, any time an object is going to be constructed by code outside of your control, CompositionInitializer allows us to continue to use MEF to satisfy the import requirements of that object. In order to use this from WPF, I’ve ported the code from MEF Preview 9 and Glenn Block’s (now obsolete) PartInitializer port to Windows Presentation Foundation.  There are some subtle changes from the Silverlight port, mainly to handle running in a desktop application context.  The default behavior of my port is to construct an AggregateCatalog containing a DirectoryCatalog set to the location of the entry assembly of the application.  In addition, if an “Extensions” folder exists under the entry assembly’s directory, a second DirectoryCatalog for that folder will be included.  This behavior can be overridden by specifying a CompositionContainer or one or more ComposablePartCatalogs to the System.ComponentModel.Composition.Hosting.CompositionHost static class prior to the first use of CompositionInitializer. Please download CompositionInitializer and CompositionHost for VS 2010 RC, and contact me with any feedback. Composition.Initialization.Desktop.zip Edit on 3/29: Glenn Block has since updated his version of CompositionInitializer (and ExportFactory<T>!), and made it available here: http://cid-f8b2fd72406fb218.skydrive.live.com/self.aspx/blog/Composition.Initialization.Desktop.zip This is a .NET 3.5 solution, and should soon be pushed to CodePlex, and made available on the main MEF site.

    Read the article

  • WPF Custom ListBox as Buttons Click not firing

    - by Ryan
    I am attempting to have a ListBox of TextBoxes with click events. I have read that one way to achieve this was to have a list of Buttons and call ButtonBase.Click="" on the ListBox. This was not working. Any advice as to how I would hook up a click event to the listbox items? Thanks <Window.Resources> <ControlTemplate x:Key="MouseOverFocusTemplate" > <Grid> <Grid.RowDefinitions> <RowDefinition Height="55*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <TextBox Width="290" TextAlignment="Left" VerticalContentAlignment="Center" BorderThickness="0" BorderBrush="Transparent" Foreground="#FF6FB8FD" FontSize="24" TextWrapping="Wrap" Text="{Binding .}" Grid.Column="1" Grid.Row="1" MinHeight="55" Cursor="Hand" IsReadOnly="True" FontFamily="Arial" > <TextBox.Background> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FF013B73" Offset="0.501"/> <GradientStop Color="#FF091F34"/> <GradientStop Color="#FF014A8F" Offset="0.5"/> <GradientStop Color="#FF003363" Offset="1"/> </LinearGradientBrush> </TextBox.Background> </TextBox> </Grid> </ControlTemplate> <Style x:Key="MouseOverFocusStyle" TargetType="{x:Type TextBox}"> <Setter Property="Template" Value="{StaticResource MouseOverFocusTemplate}"/> </Style> <ControlTemplate x:Key="LostFocusTemplate" > <Grid> <Grid.RowDefinitions> <RowDefinition Height="55*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <TextBox Width="290" TextAlignment="Left" VerticalContentAlignment="Center" BorderThickness="0" BorderBrush="Transparent" Foreground="#FF6FB8FD" FontSize="24" TextWrapping="Wrap" Text="{Binding .}" Grid.Column="1" Grid.Row="1" MinHeight="55" Cursor="Hand" IsReadOnly="True" FontFamily="Arial" > <TextBox.Background> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <LinearGradientBrush.RelativeTransform> <TransformGroup> <ScaleTransform CenterX="0.5" CenterY="0.5"/> <SkewTransform CenterX="0.5" CenterY="0.5"/> <RotateTransform CenterX="0.5" CenterY="0.5"/> <TranslateTransform/> </TransformGroup> </LinearGradientBrush.RelativeTransform> <GradientStop Color="#FF091F34" Offset="1"/> <GradientStop Color="#FF002F5C" Offset="0.4"/> </LinearGradientBrush> </TextBox.Background> </TextBox> </Grid> </ControlTemplate> <Style x:Key="LostFocusStyle" TargetType="{x:Type TextBox}"> <Setter Property="Template" Value="{StaticResource LostFocusTemplate}"/> </Style> <ControlTemplate x:Key="GotFocusTemplate" > <Grid> <Grid.RowDefinitions> <RowDefinition Height="55*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <TextBox Width="290" TextAlignment="Left" VerticalContentAlignment="Center" BorderThickness="0" BorderBrush="Transparent" Foreground="#FFE38E27" FontSize="24" TextWrapping="Wrap" Text="{Binding .}" Grid.Column="1" Grid.Row="1" MinHeight="55" Cursor="Hand" IsReadOnly="True" FontFamily="Arial" > <TextBox.Background> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="Black" Offset="0.501"/> <GradientStop Color="#FF091F34"/> <GradientStop Color="#FF002F5C" Offset="0.5"/> </LinearGradientBrush> </TextBox.Background> </TextBox> </Grid> </ControlTemplate> <Style x:Key="GotFocusStyle" TargetType="{x:Type TextBox}"> <Setter Property="Template" Value="{StaticResource GotFocusTemplate}"/> </Style> <Style TargetType="{x:Type Button}" x:Key="listButton"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Border BorderBrush="Black" BorderThickness="1" Margin="-2,0,0,-1"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="55*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Grid.RenderTransform> <TransformGroup> <ScaleTransform ScaleX="1" ScaleY="1"/> <SkewTransform AngleX="0" AngleY="0"/> <RotateTransform Angle="0"/> <TranslateTransform X="0" Y="0"/> </TransformGroup> </Grid.RenderTransform> <!--<ScrollViewer x:Name="PART_ContentHost" />--> <TextBox Width="290" TextAlignment="Left" VerticalContentAlignment="Center" BorderThickness="0" BorderBrush="Transparent" Foreground="#FF6FB8FD" FontSize="24" Style="{StaticResource LostFocusStyle}" TextWrapping="Wrap" Text="{Binding .}" Grid.Column="1" Grid.Row="1" MinHeight="55" Cursor="Hand" IsReadOnly="True" FontFamily="Arial" Name="bar" > <TextBox.Background> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <LinearGradientBrush.RelativeTransform> <TransformGroup> <ScaleTransform CenterX="0.5" CenterY="0.5"/> <SkewTransform CenterX="0.5" CenterY="0.5"/> <RotateTransform CenterX="0.5" CenterY="0.5"/> <TranslateTransform/> </TransformGroup> </LinearGradientBrush.RelativeTransform> <GradientStop Color="#FF091F34" Offset="1"/> <GradientStop Color="#FF002F5C" Offset="0.4"/> </LinearGradientBrush> </TextBox.Background> </TextBox> </Grid> </Border> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="true"> <Setter TargetName="bar" Property="Style" Value="{StaticResource MouseOverFocusStyle}" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> <DataTemplate x:Key="CustomListData" DataType="{x:Type ListBoxItem}"> <Button Style="{StaticResource listButton}" /> </DataTemplate> </Window.Resources> <Window.DataContext> <ObjectDataProvider ObjectType="{x:Type local:ImageLoader}" MethodName="LoadImages" /> </Window.DataContext> <ListBox ItemsSource="{Binding}" Width="320" Background="#FF021422" BorderBrush="#FF1C4B79"> <ListBox.Resources> <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}">Transparent</SolidColorBrush> <Style TargetType="{x:Type ListBox}"> <Setter Property="ItemTemplate" Value="{StaticResource CustomListData }" /> <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" /> </Style> </ListBox.Resources> </ListBox>

    Read the article

  • WPF TextBox SpellChecking Problem

    - by Alex
    How can I change the spellchecking language of a WPF textbox to french using XAML? I tried this but it doesn't work. <TextBox AcceptsReturn="true" SpellCheck.IsEnabled="true" FontSize="12" BorderBrush="Blue" Height="100" Language="fr-fr" /> French is supposed to be one of the 4 supported languages for spellchecking in WPF so I don't understand why it doesn't work. I also tried fr-CA but it still won't work.

    Read the article

  • WPF: Drag/Drop to re-order grid and jiggle

    - by Echilon
    I need to implement a grid in WPF which has squares that can be dragged/dropped to be re-ordered, but I'm not sure the best way to do it. I was thinking using an ObservableCollection of squares and a UniFormGrid but although I have experience with both WPF and drag/drop, ideally I'd like to do a kind of 'jiggle' when before the user releases the mouse. Any suggestions on a good starting point?

    Read the article

  • WPF: Restyling a window?

    - by mark smith
    Hi there, does anyone know if its possible to restyle a window in wpf. Or even better any tutorials or samples? Basically i would like to change the minimize and maximize buttons - oh and the close button to be slightly bigger.... I have expression blend.... Is this possible? I saw some samples in infragistics sample apps which have some great looking forms and as far as i can tell it doesn't use any custom wpf controls... Any ideas really appreciated

    Read the article

  • WPF Login Verification Using Active Directory

    - by psheriff
    Back in October of 2009 I created a WPF login screen (Figure 1) that just showed how to create the layout for a login screen. That one sample is probably the most downloaded sample we have. So in this blog post, I thought I would update that screen and also hook it up to show how to authenticate your user against Active Directory. Figure 1: Original WPF Login Screen I have updated not only the code behind for this login screen, but also the look and feel as shown in Figure 2. Figure 2: An Updated WPF Login Screen The UI To create the UI for this login screen you can refer to my October of 2009 blog post to see how to create the borderless window. You can then look at the sample code to see how I created the linear gradient brush for the background. There are just a few differences in this screen compared to the old version. First, I changed the key image and instead of using words for the Cancel and Login buttons, I used some icons. Secondly I added a text box to hold the Domain name that you wish to authenticate against. This text box is automatically filled in if you are connected to a network. In the Window_Loaded event procedure of the winLogin window you can retrieve the user’s domain name from the Environment.UserDomainName property. For example: txtDomain.Text = Environment.UserDomainName The ADHelper Class Instead of coding the call to authenticate the user directly in the login screen I created an ADHelper class. This will make it easier if you want to add additional AD calls in the future. The ADHelper class contains just one method at this time called AuthenticateUser. This method authenticates a user name and password against the specified domain. The login screen will gather the credentials from the user such as their user name and password, and also the domain name to authenticate against. To use this ADHelper class you will need to add a reference to the System.DirectoryServices.dll in .NET. The AuthenticateUser Method In order to authenticate a user against your Active Directory you will need to supply a valid LDAP path string to the constructor of the DirectoryEntry class. The LDAP path string will be in the format LDAP://DomainName. You will also pass in the user name and password to the constructor of the DirectoryEntry class as well. With a DirectoryEntry object populated with this LDAP path string, the user name and password you will now pass this object to the constructor of a DirectorySearcher object. You then perform the FindOne method on the DirectorySearcher object. If the DirectorySearcher object returns a SearchResult then the credentials supplied are valid. If the credentials are not valid on the Active Directory then an exception is thrown. C#public bool AuthenticateUser(string domainName, string userName,  string password){  bool ret = false;   try  {    DirectoryEntry de = new DirectoryEntry("LDAP://" + domainName,                                           userName, password);    DirectorySearcher dsearch = new DirectorySearcher(de);    SearchResult results = null;     results = dsearch.FindOne();     ret = true;  }  catch  {    ret = false;  }   return ret;} Visual Basic Public Function AuthenticateUser(ByVal domainName As String, _ ByVal userName As String, ByVal password As String) As Boolean  Dim ret As Boolean = False   Try    Dim de As New DirectoryEntry("LDAP://" & domainName, _                                 userName, password)    Dim dsearch As New DirectorySearcher(de)    Dim results As SearchResult = Nothing     results = dsearch.FindOne()     ret = True  Catch    ret = False  End Try   Return retEnd Function In the Click event procedure under the Login button you will find the following code that will validate the credentials that the user types into the login window. C#private void btnLogin_Click(object sender, RoutedEventArgs e){  ADHelper ad = new ADHelper();   if(ad.AuthenticateUser(txtDomain.Text,         txtUserName.Text, txtPassword.Password))    DialogResult = true;  else    MessageBox.Show("Unable to Authenticate Using the                      Supplied Credentials");} Visual BasicPrivate Sub btnLogin_Click(ByVal sender As Object, _ ByVal e As RoutedEventArgs)  Dim ad As New ADHelper()   If ad.AuthenticateUser(txtDomain.Text, txtUserName.Text, _                         txtPassword.Password) Then    DialogResult = True  Else    MessageBox.Show("Unable to Authenticate Using the                      Supplied Credentials")  End IfEnd Sub Displaying the Login Screen At some point when your application launches, you will need to display your login screen modally. Below is the code that you would call to display the login form (named winLogin in my sample application). This code is called from the main application form, and thus the owner of the login screen is set to “this”. You then call the ShowDialog method on the login screen to have this form displayed modally. After the user clicks on one of the two buttons you need to check to see what the DialogResult property was set to. The DialogResult property is a nullable type and thus you first need to check to see if the value has been set. C# private void DisplayLoginScreen(){  winLogin win = new winLogin();   win.Owner = this;  win.ShowDialog();  if (win.DialogResult.HasValue && win.DialogResult.Value)    MessageBox.Show("User Logged In");  else    this.Close();} Visual Basic Private Sub DisplayLoginScreen()  Dim win As New winLogin()   win.Owner = Me  win.ShowDialog()  If win.DialogResult.HasValue And win.DialogResult.Value Then    MessageBox.Show("User Logged In")  Else    Me.Close()  End IfEnd Sub Summary Creating a nice looking login screen is fairly simple to do in WPF. Using the Active Directory services from a WPF application should make your desktop programming task easier as you do not need to create your own user authentication system. I hope this article gave you some ideas on how to create a login screen in WPF. NOTE: You can download the complete sample code for this blog entry at my website: http://www.pdsa.com/downloads. Click on Tips & Tricks, then select 'WPF Login Verification Using Active Directory' from the drop down list. 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 opening up exe program within WPF window

    - by SwiftLion
    Not sure if this is possible but is there a way to open up another program like notepad within the container of a WPF window? similiar to that of being able to open a web page using the webbrowser control? Basically I would like to open notepad or other exe but keep it constrained within the WPF window container using xaml/c# code? not sure if possible?

    Read the article

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