Search Results

Search found 6871 results on 275 pages for 'wpf xaml'.

Page 7/275 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • how to tile 3D mesh with image brush in XAML

    - by MC9000
    I have a 2D square in a ViewPort3D that I want to do a tiling of an image (like a checkerboard or flooring with "tiles" effect). I've created an image brush (the image is 50x50 pixels, the surface 250x550 pixels) and a viewport (trying to follow MS's site - though their example is for 2D), but only 1 of the colors in the "tile" image shows up and no tiling is seen. I can't find a single example on the Internet and MS's site has no info (that I can find) on 3D XAML anywhere, so I'm stumped as how to actually do this. <Viewport3D> <Viewport3D.Camera> <PerspectiveCamera Position="125,790,120" LookDirection="0,-.7,-0.25" UpDirection="0,0,1" /> </Viewport3D.Camera> <ModelVisual3D> <ModelVisual3D.Content> <Model3DGroup> <AmbientLight Color="white" /> <GeometryModel3D> <GeometryModel3D.Geometry> <MeshGeometry3D Positions="0,0,0 250,0,0 250,550,0 0,550,0 " TriangleIndices="0 1 3 1 2 3 "/> </GeometryModel3D.Geometry> <GeometryModel3D.Material> <DiffuseMaterial> <DiffuseMaterial.Brush> <ImageBrush ViewportUnits="Absolute" TileMode="Tile" ImageSource="testsquare.gif" Viewport="0,0,50,50" Stretch="None" ViewboxUnits="Absolute" /> </DiffuseMaterial.Brush> </DiffuseMaterial> </GeometryModel3D.Material> </GeometryModel3D> </Model3DGroup> </ModelVisual3D.Content> </ModelVisual3D> </Viewport3D>

    Read the article

  • Bizarre problem with WPF XAML file.

    - by paxdiablo
    I've just started a very simple WPF application which consists of a main large image and four smaller images. In order to assist with the layout, I created some JPEGs in MsPaint containing the images -2, -1, 0, +1 and +2 and just copied them into the top level of the project directory. The XAML segment contains, for the five images: <Image Grid.Column="1" Grid.Row="2" Grid.ColumnSpan="4" Grid.RowSpan="1" Margin="0,0,0,0" Name="imgPicture" Stretch="Fill" VerticalAlignment="Top" Source="file:///C:/DAndS/Pax/MyDocs/VS2008/Projects/MyProj/zero.jpg" <Image Grid.Column="1" Grid.Row="4" Grid.ColumnSpan="1" Grid.RowSpan="1" Margin="0,0,0,0" Name="imgPicMinus2" Stretch="Fill" VerticalAlignment="Top" Source="file:///C:/DAndS/Pax/MyDocs/VS2008/Projects/MyProj/minus2.jpg" <Image Grid.Column="2" Grid.Row="4" Grid.ColumnSpan="1" Grid.RowSpan="1" Margin="0,0,0,0" Name="imgPicMinus1" Stretch="Fill" VerticalAlignment="Top" Source="file:///C:/DAndS/Pax/MyDocs/VS2008/Projects/MyProj/minus1.jpg" <Image Grid.Column="3" Grid.Row="4" Grid.ColumnSpan="1" Grid.RowSpan="1" Margin="0,0,0,0" Name="imgPicPlus1" Stretch="Fill" VerticalAlignment="Top" Source="file:///C:/DAndS/Pax/MyDocs/VS2008/Projects/MyProj/plus1.jpg" <Image Grid.Column="4" Grid.Row="4" Grid.ColumnSpan="1" Grid.RowSpan="1" Margin="0,0,0,0" Name="imgPicPlus2" Stretch="Fill" VerticalAlignment="Top" Source="file:///C:/DAndS/Pax/MyDocs/VS2008/Projects/MyProj/plus2.jpg" When I try to set the source property for the plus2 image, it complains with a dialog box stating: Property value is not valid. Details | V The file plus2.jpg is not part of the project or its 'Build Action' property is not set to 'Resource'. Yet if I rename the file to plus3.jpg or plus2x.jpg, I don't have that problem. Why is it complaining about plus2.jpg specifically?

    Read the article

  • C# XAML get new width and height for Canvas

    - by Jack Navarro
    I have searched through many times but have not seen this before. Probably really simple question but can't wrap my head around it. Wrote a VSTO add-in for Excel that draws a Grid dynamically. Then launches a new window and replaces the contents of the Canvas with the generated Grid. The problem is with printing. When I call the print procedure the canvas.height and canvas.width returned is the old value prior to replacing it with the grid. Sample: string="<Grid Name=\"CanvasGrid\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">..Lots of stuff..</Grid>"; // Launch new window and replace the Canvas element WpfUserControl newWindow = new WpfUserControl(); newWindow.Show(); //To test MessageBox.Show(myCanvas.ActualWidth.ToString()); //return 894 Grid testGrid = myCanvas.FindName("CanvasGrid") as Grid; MessageBox.Show("Grid " + testGrid.ActualWidth.ToString()); //return 234 StringReader stringReader = new StringReader(LssAllcChrt); XmlReader xmlReader = XmlReader.Create(stringReader); Canvas myCanvas = newWindow.FindName("GrphCnvs") as Canvas; myCanvas.Children.Clear(); myCanvas.Children.Add((UIElement)XamlReader.Load(xmlReader)); //To test MessageBox.Show(myCanvas.ActualWidth.ToString()); //return 894 but should be much larger the Grid spans all three of my screens Grid testGrid = myCanvas.FindName("CanvasGrid") as Grid; MessageBox.Show("Grid " + testGrid.ActualWidth.ToString()); //return 234 but should be much larger the Grid spans all three of my screens //Run code from WpfUserControl.cs after it loads from button click Grid testGrid = canvas.FindName("CanvasGrid") as Grid; MessageBox.Show("Grid " + testGrid.ActualWidth.ToString()); //return 234 but should be much larger the Grid spans all three of my screens So basically I have no way of telling what my new width and height are Any Ideas

    Read the article

  • XAML get new width and height for Canvas

    - by Jack Navarro
    I have searched through many times but have not seen this before. Probably really simple question but can't wrap my head around it. Wrote a VSTO add-in for Excel that draws a Grid dynamically. Then launches a new window and replaces the contents of the Canvas with the generated Grid. The problem is with printing. When I call the print procedure the canvas.height and canvas.width returned is the old value prior to replacing it with the grid. Sample: string="<Grid Name=\"CanvasGrid\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">..Lots of stuff..</Grid>"; // Launch new window and replace the Canvas element WpfUserControl newWindow = new WpfUserControl(); newWindow.Show(); //To test MessageBox.Show(myCanvas.ActualWidth.ToString()); //return 894 Grid testGrid = myCanvas.FindName("CanvasGrid") as Grid; MessageBox.Show("Grid " + testGrid.ActualWidth.ToString()); //return 234 StringReader stringReader = new StringReader(LssAllcChrt); XmlReader xmlReader = XmlReader.Create(stringReader); Canvas myCanvas = newWindow.FindName("GrphCnvs") as Canvas; myCanvas.Children.Clear(); myCanvas.Children.Add((UIElement)XamlReader.Load(xmlReader)); //To test MessageBox.Show(myCanvas.ActualWidth.ToString()); //return 894 but should be much larger the Grid spans all three of my screens Grid testGrid = myCanvas.FindName("CanvasGrid") as Grid; MessageBox.Show("Grid " + testGrid.ActualWidth.ToString()); //return 234 but should be much larger the Grid spans all three of my screens //Run code from WpfUserControl.cs after it loads from button click Grid testGrid = canvas.FindName("CanvasGrid") as Grid; MessageBox.Show("Grid " + testGrid.ActualWidth.ToString()); //return 234 but should be much larger the Grid spans all three of my screens So basically I have no way of telling what my new width and height are.

    Read the article

  • Why won't my WPF XAML Grid TranslateTransform.X ?

    - by George
    I'm able to change the width/height of the grid using this, so why won't it work when I use (Grid.RenderTransform).TranslateTransform.X as such: <Window.Triggers> <EventTrigger RoutedEvent="Button.Click" SourceName="button"> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty="(Grid.RenderTransform).(TranslateTransform.X)" From="0" To="200" Storyboard.TargetName="grid" Duration="0:0:2" /> </Storyboard> </BeginStoryboard> </EventTrigger> </Window.Triggers> The application loads etc, but nothing happens when the button is clicked. Here is the XAML for my grid: <Grid x:Name="grid" Height="714" Canvas.Left="240" Canvas.Top="8" Width="360" RenderTransformOrigin="0.5,0.5"> <Grid.Background> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="Black" Offset="0"/> <GradientStop Color="White" Offset="1"/> </LinearGradientBrush> </Grid.Background> <Grid.ColumnDefinitions> <ColumnDefinition Width="0*"/> <ColumnDefinition/> </Grid.ColumnDefinitions> </Grid> Note that I've tried many different Canvas.Left values, to no avail.

    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 do I stop inheritance in xaml?

    - by cfouche
    Hi Let's say I have some Control that has been disabled. It contains a bunch of elements, but I want one of those child elements to remain enabled. Something like this: <ContentControl IsEnabled="False"> <Border> <Button Content="Button" IsEnabled="True"/> </Border> </ContentControl> So in this example, the Button's IsEnabled="True" setting gets overridden by its parent. Is there a way of stopping this from happening? This seems like a strange thing to be doing, but I have a situation where, when a Control is disabled and a user mouses down on it, I still want an event to be triggered. I read in WPF Unleashed that wrapping something in a Frame control, "..isolates the content from the rest of the UI [and] properties that would normally be inherited down the element tree stop when they reach the Frame", but wrapping the Button in the example above in a Frame doesn't work. Am I on the wrong track here?

    Read the article

  • Why is my namespace not recognized in Visual Studio / xaml

    - by msfanboy
    Hello, these are my 2 classes a Attachable Property SelectedItems: code is from here: http://stackoverflow.com/questions/1297643/sync-selecteditems-in-a-muliselect-listbox-with-a-collection-in-viewmodel The namespace TBM.Helper is for sure proper as it works for other classes too. The namespace reference is also in the xaml file: xmlns:Helper="clr_namespace:TBM.Helper" But <ListBox Helper:SelectedItems.Items="{Binding SelectedItems}" ... does not work because = The property 'SelectedItems.Items' does not exist in XML namespace 'clr_namespace:TBM.Helper'. The attachable property 'Items' was not found in type 'SelectedItems What do I have to change ? using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Controls; using System.Collections; using System.Windows; namespace TBM.Helper { public static class SelectedItems : DependencyObject { private static readonly DependencyProperty SelectedItemsBehaviorProperty = DependencyProperty.RegisterAttached( "SelectedItemsBehavior", typeof(SelectedItemsBehavior), typeof(ListBox), null); public static readonly DependencyProperty ItemsProperty = DependencyProperty.RegisterAttached( "Items", typeof(IList), typeof(SelectedItems), new PropertyMetadata(null, ItemsPropertyChanged)); public static void SetItems(ListBox listBox, IList list) { listBox.SetValue(ItemsProperty, list); } public static IList GetItems(ListBox listBox) { return listBox.GetValue(ItemsProperty) as IList; } private static void ItemsPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var target = d as ListBox; if (target != null) { GetOrCreateBehavior(target, e.NewValue as IList); } } private static SelectedItemsBehavior GetOrCreateBehavior(ListBox target, IList list) { var behavior = target.GetValue(SelectedItemsBehaviorProperty) as SelectedItemsBehavior; if (behavior == null) { behavior = new SelectedItemsBehavior(target, list); target.SetValue(SelectedItemsBehaviorProperty, behavior); } return behavior; } } } using System.Windows; using System.Windows.Controls; using System.Collections; namespace TBM.Helper { public class SelectedItemsBehavior { private readonly ListBox _listBox; private readonly IList _boundList; public SelectedItemsBehavior(ListBox listBox, IList boundList) { _boundList = boundList; _listBox = listBox; SetSelectedItems(); _listBox.SelectionChanged += OnSelectionChanged; _listBox.DataContextChanged += OnDataContextChanged; } private void SetSelectedItems() { _listBox.SelectedItems.Clear(); foreach (object item in _boundList) { // References in _boundList might not be the same as in _listBox.Items int i = _listBox.Items.IndexOf(item); if (i >= 0) _listBox.SelectedItems.Add(_listBox.Items[i]); } } private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { SetSelectedItems(); } private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) { _boundList.Clear(); foreach (var item in _listBox.SelectedItems) _boundList.Add(item); } } }

    Read the article

  • Introducing Visual WebGui's XAML programming model extension for web developers

    - by Visual WebGui
    While ASP.NET provides an event base approach it is completely dismissed when working with AJAX and the richness of the server is lost and replaced with JavaScript programming and couple with a very high security risk. Visual WebGui reinstates the power of the server to AJAX development and provides a statefull yet scalable, server centric architecture that provides the benefits and user productivity of AJAX with the security and developer productivity we had before AJAX stormed into our lives. When...(read more)

    Read the article

  • Implementing Ads on any page in your Windows 8 XAML app–part 2

    - by nmarun
    In my previous article , you saw how you can start implementing ads on some of the page templates. In this one, we’ll see how we can add something called ‘interstitial ads’ – ads that appear as part of the content in your app. I have added a Grouped Items page to my project. My data model is set to show a few appliances. I have a BaseModel class and the ApplianceModel that inherits the BaseModel class has two properties to represent an appliance. The ProductHolder acts as a container for a list of...(read more)

    Read the article

  • Implementing Ads on any page in your Windows 8 XAML app–part 1

    - by nmarun
    Let’s look at how you can implements ads on any page in your win 8 app. Before you get to your application, you need to create Ad Units in the MS Pubcenter site. Once you have set up your account with payout and tax details, go to the Setup tab and you’ll see something like below. There are a few options for the sizes of the ad units as shown on the Pubcenter site. Remember that these screenshots are just to give you some reference. The actual positioning of the ads in your apps is decided by you...(read more)

    Read the article

  • xaml : Retrigger opacity animation on multiple conditions

    - by Sdry
    I have a problem figuring out how datatriggers and multidatatriggers work. I am trying to display a message, and depending on the type of message keep it displayed( + having a background), or having it fade out by a double animation on the opacity property (+ having a transparent background). My xaml view has a game object as datacontext, which has a dependency property of type GameMessage, of which the constructor looks like this: public GameMessage(bool containsMessage, string message, bool canFadeAway) { ContainsMessage = containsMessage; Message = message; CanFadeAway = canFadeAway; } pretty straight forward, I want to display the message when ContainsMessage =equals true, and trigger a fade out animation if canFadeAway equals true. But also set the background based on canFadeAway. <Canvas Name="messageCanvas" Width="300" Height="100" Style="{StaticResource fadeInOut}"> <TextBlock Name="txtMessage" Text="{Binding Path=GameMessage.Message}" Canvas.Top="25" Canvas.Left="0" Foreground="{StaticResource MessageForegroundBrush}"> </TextBlock> </Canvas> Now, the Style and triggers is where I get into trouble: <Style.Triggers> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Path=GameMessage.ContainsMessage}" Value="True"/> <Condition Binding="{Binding Path=GameMessage.CanFadeAway}" Value="False"/> </MultiDataTrigger.Conditions> <Setter Property="Background" Value="{StaticResource MessageBackgroundBrush}" /> <Setter Property="Opacity" Value="8" /> </MultiDataTrigger> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Path=GameMessage.ContainsMessage}" Value="True"/> <Condition Binding="{Binding Path=GameMessage.CanFadeAway}" Value="True"/> </MultiDataTrigger.Conditions> <Setter Property="Background" Value="Transparent" /> <Setter Property="Opacity" Value="8" /> </MultiDataTrigger> <DataTrigger Binding="{Binding Path=GameMessage.CanFadeAway}" Value="True"> <DataTrigger.EnterActions> <BeginStoryboard > <Storyboard BeginTime="0:0:0" > <DoubleAnimation Storyboard.TargetProperty="Opacity" From="8" To="0" Duration="0:0:1" BeginTime="0:0:0" /> </Storyboard> </BeginStoryboard> </DataTrigger.EnterActions> <DataTrigger.ExitActions> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty="Opacity" To="8" Duration="0:0:0.1" /> </Storyboard> </BeginStoryboard> </DataTrigger.ExitActions> </DataTrigger> </Style.Triggers> </Style> The problem is in resetting the opacity when the GameMessage Property ( of type GameMessage) is of type true,msg",true, and gets replaced by a GameMessage object of the same kind. The opcacity remains 0, and messages only get restored again when I have a message of kind true,"msg,false. After the animation, the opacity is 0, and where I would expect the second multidatatrigger to set it back to 8, and then have the animation performed by the Datatrigger, it doesnt. What would be the best way to get this working ?

    Read the article

  • A Communication System for XAML Applications

    - by psheriff
    In any application, you want to keep the coupling between any two or more objects as loose as possible. Coupling happens when one class contains a property that is used in another class, or uses another class in one of its methods. If you have this situation, then this is called strong or tight coupling. One popular design pattern to help with keeping objects loosely coupled is called the Mediator design pattern. The basics of this pattern are very simple; avoid one object directly talking to another object, and instead use another class to mediate between the two. As with most of my blog posts, the purpose is to introduce you to a simple approach to using a message broker, not all of the fine details. IPDSAMessageBroker Interface As with most implementations of a design pattern, you typically start with an interface or an abstract base class. In this particular instance, an Interface will work just fine. The interface for our Message Broker class just contains a single method “SendMessage” and one event “MessageReceived”. public delegate void MessageReceivedEventHandler( object sender, PDSAMessageBrokerEventArgs e); public interface IPDSAMessageBroker{  void SendMessage(PDSAMessageBrokerMessage msg);   event MessageReceivedEventHandler MessageReceived;} PDSAMessageBrokerMessage Class As you can see in the interface, the SendMessage method requires a type of PDSAMessageBrokerMessage to be passed to it. This class simply has a MessageName which is a ‘string’ type and a MessageBody property which is of the type ‘object’ so you can pass whatever you want in the body. You might pass a string in the body, or a complete Customer object. The MessageName property will help the receiver of the message know what is in the MessageBody property. public class PDSAMessageBrokerMessage{  public PDSAMessageBrokerMessage()  {  }   public PDSAMessageBrokerMessage(string name, object body)  {    MessageName = name;    MessageBody = body;  }   public string MessageName { get; set; }   public object MessageBody { get; set; }} PDSAMessageBrokerEventArgs Class As our message broker class will be raising an event that others can respond to, it is a good idea to create your own event argument class. This class will inherit from the System.EventArgs class and add a couple of additional properties. The properties are the MessageName and Message. The MessageName property is simply a string value. The Message property is a type of a PDSAMessageBrokerMessage class. public class PDSAMessageBrokerEventArgs : EventArgs{  public PDSAMessageBrokerEventArgs()  {  }   public PDSAMessageBrokerEventArgs(string name,     PDSAMessageBrokerMessage msg)  {    MessageName = name;    Message = msg;  }   public string MessageName { get; set; }   public PDSAMessageBrokerMessage Message { get; set; }} PDSAMessageBroker Class Now that you have an interface class and a class to pass a message through an event, it is time to create your actual PDSAMessageBroker class. This class implements the SendMessage method and will also create the event handler for the delegate created in your Interface. public class PDSAMessageBroker : IPDSAMessageBroker{  public void SendMessage(PDSAMessageBrokerMessage msg)  {    PDSAMessageBrokerEventArgs args;     args = new PDSAMessageBrokerEventArgs(      msg.MessageName, msg);     RaiseMessageReceived(args);  }   public event MessageReceivedEventHandler MessageReceived;   protected void RaiseMessageReceived(    PDSAMessageBrokerEventArgs e)  {    if (null != MessageReceived)      MessageReceived(this, e);  }} The SendMessage method will take a PDSAMessageBrokerMessage object as an argument. It then creates an instance of a PDSAMessageBrokerEventArgs class, passing to the constructor two items: the MessageName from the PDSAMessageBrokerMessage object and also the object itself. It may seem a little redundant to pass in the message name when that same message name is part of the message, but it does make consuming the event and checking for the message name a little cleaner – as you will see in the next section. Create a Global Message Broker In your WPF application, create an instance of this message broker class in the App class located in the App.xaml file. Create a public property in the App class and create a new instance of that class in the OnStartUp event procedure as shown in the following code: public partial class App : Application{  public PDSAMessageBroker MessageBroker { get; set; }   protected override void OnStartup(StartupEventArgs e)  {    base.OnStartup(e);     MessageBroker = new PDSAMessageBroker();  }} Sending and Receiving Messages Let’s assume you have a user control that you load into a control on your main window and you want to send a message from that user control to the main window. You might have the main window display a message box, or put a string into a status bar as shown in Figure 1. Figure 1: The main window can receive and send messages The first thing you do in the main window is to hook up an event procedure to the MessageReceived event of the global message broker. This is done in the constructor of the main window: public MainWindow(){  InitializeComponent();   (Application.Current as App).MessageBroker.     MessageReceived += new MessageReceivedEventHandler(       MessageBroker_MessageReceived);} One piece of code you might not be familiar with is accessing a property defined in the App class of your XAML application. Within the App.Xaml file is a class named App that inherits from the Application object. You access the global instance of this App class by using Application.Current. You cast Application.Current to ‘App’ prior to accessing any of the public properties or methods you defined in the App class. Thus, the code (Application.Current as App).MessageBroker, allows you to get at the MessageBroker property defined in the App class. In the MessageReceived event procedure in the main window (shown below) you can now check to see if the MessageName property of the PDSAMessageBrokerEventArgs is equal to “StatusBar” and if it is, then display the message body into the status bar text block control. void MessageBroker_MessageReceived(object sender,   PDSAMessageBrokerEventArgs e){  switch (e.MessageName)  {    case "StatusBar":      tbStatus.Text = e.Message.MessageBody.ToString();      break;  }} In the Page 1 user control’s Loaded event procedure you will send the message “StatusBar” through the global message broker to any listener using the following code: private void UserControl_Loaded(object sender,  RoutedEventArgs e){  // Send Status Message  (Application.Current as App).MessageBroker.    SendMessage(new PDSAMessageBrokerMessage("StatusBar",      "This is Page 1"));} Since the main window is listening for the message ‘StatusBar’, it will display the value “This is Page 1” in the status bar at the bottom of the main window. Sending a Message to a User Control The previous example sent a message from the user control to the main window. You can also send messages from the main window to any listener as well. Remember that the global message broker is really just a broadcaster to anyone who has hooked into the MessageReceived event. In the constructor of the user control named ucPage1 you can hook into the global message broker’s MessageReceived event. You can then listen for any messages that are sent to this control by using a similar switch-case structure like that in the main window. public ucPage1(){  InitializeComponent();   // Hook to the Global Message Broker  (Application.Current as App).MessageBroker.    MessageReceived += new MessageReceivedEventHandler(      MessageBroker_MessageReceived);} void MessageBroker_MessageReceived(object sender,  PDSAMessageBrokerEventArgs e){  // Look for messages intended for Page 1  switch (e.MessageName)  {    case "ForPage1":      MessageBox.Show(e.Message.MessageBody.ToString());      break;  }} Once the ucPage1 user control has been loaded into the main window you can then send a message using the following code: private void btnSendToPage1_Click(object sender,  RoutedEventArgs e){  PDSAMessageBrokerMessage arg =     new PDSAMessageBrokerMessage();   arg.MessageName = "ForPage1";  arg.MessageBody = "Message For Page 1";   // Send a message to Page 1  (Application.Current as App).MessageBroker.SendMessage(arg);} Since the MessageName matches what is in the ucPage1 MessageReceived event procedure, ucPage1 can do anything in response to that event. It is important to note that when the message gets sent it is sent to all MessageReceived event procedures, not just the one that is looking for a message called “ForPage1”. If the user control ucPage1 is not loaded and this message is broadcast, but no other code is listening for it, then it is simply ignored. Remove Event Handler In each class where you add an event handler to the MessageReceived event you need to make sure to remove those event handlers when you are done. Failure to do so can cause a strong reference to the class and thus not allow that object to be garbage collected. In each of your user control’s make sure in the Unloaded event to remove the event handler. private void UserControl_Unloaded(object sender, RoutedEventArgs e){  if (_MessageBroker != null)    _MessageBroker.MessageReceived -=         _MessageBroker_MessageReceived;} Problems with Message Brokering As with most “global” classes or classes that hook up events to other classes, garbage collection is something you need to consider. Just the simple act of hooking up an event procedure to a global event handler creates a reference between your user control and the message broker in the App class. This means that even when your user control is removed from your UI, the class will still be in memory because of the reference to the message broker. This can cause messages to still being handled even though the UI is not being displayed. It is up to you to make sure you remove those event handlers as discussed in the previous section. If you don’t, then the garbage collector cannot release those objects. Instead of using events to send messages from one object to another you might consider registering your objects with a central message broker. This message broker now becomes a collection class into which you pass an object and what messages that object wishes to receive. You do end up with the same problem however. You have to un-register your objects; otherwise they still stay in memory. To alleviate this problem you can look into using the WeakReference class as a method to store your objects so they can be garbage collected if need be. Discussing Weak References is beyond the scope of this post, but you can look this up on the web. Summary In this blog post you learned how to create a simple message broker system that will allow you to send messages from one object to another without having to reference objects directly. This does reduce the coupling between objects in your application. You do need to remember to get rid of any event handlers prior to your objects going out of scope or you run the risk of having memory leaks and events being called even though you can no longer access the object that is responding to that event. 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 Communication System for XAML Applications” from the drop down list.

    Read the article

  • XAML | When used XamlReader.Parse, not able to refer the items using the LogicalTreeHelper/VisualTre

    - by Roopesh
    Hi, I am setting the dynamic xaml (I am reading the xaml from the DB) for the content of a tab using the below statement. Tab.Content = XamlReader.Parse(xaml, ctx) After setting the content, if I try getting the children using the VisualTreeHelper, but I am not able to get. How ever I dont have this issue when I construct the xaml statically. Here is the code to reading the xaml. Dim XmlDocument = New XmlDataDocument() Dim IID As String = Nothing Dim xaml As String = Nothing Dim Tab As New TabItem Dim TempPanel As XmlNode = Nothing 'Tab.Height = 0 Try XmlDocument.Load(Directory.GetCurrentDirectory & "\Xml\AppFile.xml") pXmlDoc = XmlDocument xaml = XmlDocument.SelectSingleNode("//Grid").OuterXml Dim AsmName As String = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name Dim ctx As ParserContext = New ParserContext() ' New ParserContext() ctx.XamlTypeMapper = New XamlTypeMapper(New String() {AsmName}) ctx.XamlTypeMapper.AddMappingProcessingInstruction("src", "WpfToolkitDataGridTester", AsmName) ctx.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation") ctx.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml") ctx.XmlnsDictionary.Add("src", "clr-namespace:WpfToolkitDataGridTester;assembly=" + AsmName) Tab.Name = "Tab" & Grid1Tab.Items.Count + 1 Tab.Header = "AppFile-1" Tab.BorderThickness = New Thickness(0) Tab.IsSelected = True Tab.Content = XamlReader.Parse(xaml, ctx) Grid1Tab.Items.Add(Tab) Return True Catch ex As Exception Throw End Try Here is the code to access the item after constructing the XAML. For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(myVisual) - 1 Dim childVisual As Visual = CType(VisualTreeHelper.GetChild(myVisual, i), Visual) Select Case childVisual.DependencyObjectType.Name Case "ComboBox" AddHandler CType(childVisual, ComboBox).SelectionChanged, AddressOf ComboBox_SelectChanged Case "CheckBox" AddHandler CType(childVisual, CheckBox).Checked, AddressOf CheckBoxClicked AddHandler CType(childVisual, CheckBox).Unchecked, AddressOf CheckBoxClicked Case "RadioButton" AddHandler CType(childVisual, RadioButton).Checked, AddressOf CheckBoxClicked Case "TabControl" For Each item As System.Windows.Controls.TabItem In CType(childVisual, TabControl).Items EnumVisual(item.Content) Next End Select EnumVisual(childVisual) Next i any help is highly appreciated. Thanks,

    Read the article

  • WPF4 Unleashed - how does converting child elements work?

    - by Kapol
    In chapter 2 of the book WPF4 Unleashed the author shows an example of how XAML processes type conversion. He states that <SolidColorBrush>White</SolidColorBrush> is equivalent to <SolidColorBrush Color="White"/> , because a string can be converted into a SolidColorBrush object. But how is that enough? It doesn't make sense to me. How does XAML know to which property should the value White be assigned?

    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

  • 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

  • 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

  • WPF Constrain the resize of a canvas' child object to the dimensions of the canvas

    - by Scott
    Given the following XAML: <Window x:Class="AdornerTesting.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="500" Width="500" Loaded="Window_Loaded"> <Grid Name="grid"> <Canvas Name="canvas" Width="400" Height="400" Background="LightGoldenrodYellow"> <RichTextBox Name="richTextBox" Canvas.Top="10" Canvas.Left="10" BorderBrush="Black" BorderThickness="2" Width="200" Height="200" MaxWidth="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Canvas}},Path=ActualWidth}" MaxHeight="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Canvas}},Path=ActualHeight}"/> </Canvas> </Grid> </Window> and a set of adorners being added to the RichTextBox in the Loaded event like so: AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(richTextBox); adornerLayer.Add(new ResizeAdorner(richTextBox)); How do I keep from being able to resize the RichTextBox beyond the visble bounds of the Canvas? The ResizeAdorner is essentially the same code that can be found in the MSDN adorner example and it works just fine. Should I be doing something with the bindings of MaxWidth and MaxHeight in the code-behind to calculate how the RichTextBox can be resized? Or is there a way to do this in XAML?

    Read the article

  • WPF WrapPanel with some items having a height of *

    - by Aphex
    How do I make a WrapPanel with some items having a Height of *? A deceptively simple question that I have been trying to solve. I want a control (or some XAML layout magickry) that behaves similar to a Grid that has some rows with a Height of *, but supports wrapping of columns. Hell; call it a WrapGrid. :) Here's a mockup to visualize this. Imagine a grid defined as such: <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="400"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Button Grid.Row="0" MinHeight="30">I'm auto-sized.</Button> <Button Grid.Row="1" MinHeight="90">I'm star-sized.</Button> <Button Grid.Row="2" MinHeight="30">I'm auto-sized.</Button> <Button Grid.Row="3" MinHeight="90">I'm star-sized, too!</Button> <Button Grid.Row="4" MinHeight="30">I'm auto-sized.</Button> <Button Grid.Row="5" MinHeight="30">I'm auto-sized.</Button> </Grid> </Window> What I want this panel to do is wrap an item into an additional column when the item can not get any smaller than its minHeight. Here is a horrible MSPaint of some mockups I made detailing this process. Recall from the XAML that the auto-sized buttons have minHeights of 30, and the star-sized buttons have minHeights of 90. This mockup is just two grids side by side and I manually moved buttons around in the designer. Conceivably, this could be done programmatically and serve as a sort of convoluted solution to this. How can this be done? I will accept any solution whether it's through xaml or has some code-behind (though I would prefer pure XAML if possible since xaml code behind is tougher to implement in IronPython). Updated with a bounty

    Read the article

  • WPF not applying default styles defined in MergedDictionaries?

    - by Burgberger
    In a WPF application I defined default control styles in separate resource dictionaries (e.g. "ButtonStyle.xaml"), and added them as merged dictionaries to a resource dictionary named "ResDictionary.xaml". If I refer this "ResDictionary.xaml" as merged dictionary in my App.xaml, the default styles are not applied. However, if I refer the "ButtonStyle.xaml", it works correctly. If I recompile the same code in .NET 3.5 or 3.0, it recognizes and applies the default styles referred in "App.xaml" through "ResDictionary.xaml", but not in .NET 4.0. At runtime if I check the Application.Current.Resources dictionary, the default styles are there, but they are not applied, only if I specify the Style property explicitly in the Button control. Are there any solutions to refer a resource dictionary (containig default styles) this way in .NET 4.0? App.xaml: <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Styles/ResDictionary.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> ResDictionary.xaml: <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Default/ButtonStyle.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> ButtonStyle.xaml: <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Style TargetType="Button"> <Setter Property="Background" Value="Yellow"/> </Style> </ResourceDictionary>

    Read the article

  • Setting a WPF ContextMenu's PlacementTarget property in XAML?

    - by qntmfred
    <Button Name="btnFoo" Content="Foo" > <Button.ContextMenu Placement="Bottom" PlacementTarget="btnFoo"> <MenuItem Header="Bar" /> </Button.ContextMenu> </Button> gives me a runtime error 'UIElement' type does not have a public TypeConverter class I also tried <Button Name="btnFoo" Content="Foo" > <Button.ContextMenu Placement="Bottom" PlacementTarget="{Binding ElementName=btnFoo}"> <MenuItem Header="Bar" /> </Button.ContextMenu> </Button> and that put the ContextMenu in the top left corner of my screen, rather than at the Button

    Read the article

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