How to Learn about WPF secrets 01

Source: Internet
Author: User
  • In XAML, the button changes after the mouse is moved to the button:
        <Button MinWidth="75" Margin="10">                <Button.Style>                    <Style TargetType="{x:Type Button}">                        <Style.Triggers>                            <Trigger Property="IsMouseOver" Value="True">                                <Setter Property="Foreground" Value="Red"/>                            </Trigger>                        </Style.Triggers>                    </Style>                </Button.Style>                    OK    </Button>
  • Traverse and print the logical and visual trees in the debug environment:
    Public partial class aboutdialog: window {public aboutdialog () {initializecomponent (); printlogicaltree (0, this);} protected override void oncontentrendered (eventargs e) {base. oncontentrendered (E); printvisualtree (0, this);} void printlogicaltree (INT depth, object OBJ) {// print the object with preceding spaces that represent its depth debug. writeline (new string ('', depth) + OBJ); // sometim Es leaf nodes aren dependencies dependencyobjects (e.g. Strings) if (! (Obj is dependencyobject) return; // recursive call for each logical child foreach (Object child in logicaltreehelper. getchildren (OBJ as dependencyobject) printlogicaltree (depth + 1, child);} void printvisualtree (INT depth, dependencyobject OBJ) {// print the object with preceding spaces that represent its depth debug. writeline (new string ('', depth) + OBJ); // recursive call for each visual child for (INT I = 0; I <visualtreehelper. getchildrencount (OBJ); I ++) printvisualtree (depth + 1, visualtreehelper. getchild (OBJ, I ));}}

    The visible tree does not have a node until the window is finished at least once. Otherwise, it is empty. This is why printvisualtree is called in oncontentrendered, because oncontentrendered is called only after the layout is complete.

  • If you do not set the fontsize and fontstyle of the entire windows element, but set them on the internal stackpanel, these two attributes will only be inherited by the Control in stackpanel. However, moving property features to an internal stackpanel element does not have any font-related attributes. Instead, you must use the fontsize and fontstyle additional attributes, which are defined in a class called textelement. As follows:
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" TextElement.FontSize="30"></StackPanel>

  • Similar to the previous Windows Forms technology, many WPF Classes define a tag attribute (type: system. Object) to store custom data for each instance. However, to add custom data to any object derived from dependencyobject, additional attributes are more powerful and flexible. We usually ignore this point, that is, you can use additional attributes to efficiently add custom data to sealed class instances (Seal classes are everywhere in WPF ).
    For example, the tag attribute of frameworkelement is a dependency attribute, so you can attach an object instance of geometrymodel3d (which is a sealed class with no tag attribute) to it.
            GeometryModel3D model = new GeometryModel3D();        model.SetValue(FrameworkElement.TagProperty, "My costom data");

  • Although the handled attribute of routedeventargs is set to true in the event handler, the pipeline transmission or bubbling can be terminated, but each handler along the tree can still receive these events! This can only be done in procedural code. Use addhandler's overload to add a Boolean parameter handledeventstoo.
    For example:
            AddHandler(Window.MouseRightButtonDownEvent, new MouseButtonEventHandler(AboutDialog_MouseRightButtonDown), true);

    Passing true to the third parameter means that even if you right-click a listboxitem, aboutdialog_mouserightbuttondown will receive the event.
    At any time, you should avoid handling handled events as much as possible, because the events should be handled immediately. Adding a handler to the preview version of an event is a good alternative.
    In short, terminating pipeline transfer or bubbling is just an illusion. More accurately, when a routing event is marked as handled, pipeline transmission and bubbling continue, but by default, the event handler only processes events that have not been processed.

  • Use a pen event
    A pointer is a device similar to a tablet PC, and its default behavior is similar to a mouse. In other words, using it can trigger some events, such as mousemove, mousedown, and mouseup events. This line is critical to the indicator pen so that it can be used in any program, not just tablets. However, if you plan to provide an experience optimized for the indicator pen, you can handle some event specific to the indicator pen, such as stylusmove, stylusdown, and stylusup. The pointer is more skillful than the mouse, because some events of the pointer do not have corresponding mouse events, such as stylusinairmove, stylussystemgesture, stylusinrange, and stylusoutofrange. There are other ways to mine the indicator pen function without directly handling these events.

  • Where can I process the Middle-click events?
    If you browse all the mouse events provided by uielement or contentelement, you can find the mouseleftbuttondown, mouseleftbuttonup, mouserightbuttondown, and mouserightbuttonup events (and the pipeline preview version of each event ), but what should I do if some additional buttons appear on the mouse?
    This information can be obtained through the more common mousedown and mouseup events (the two events also have the corresponding preview events ). Parameters passed in such an event handler include a mousebutton enumeration value, which indicates that the mouse status has just changed. They are left, right, middle, xbutton1, or xbutton2, there is also a corresponding mousebuttonstate enumeration value, indicating whether the button is pressed or released.

  • All routeduicommand objects define a text attribute, which contains the command name and is suitable for display on the user interface. (This attribute is the only difference between routeduicommand and its base class routedcommand .) For example, the text attribute of the Help Command is (don't be surprised) The help string. The hard encoding of content on this button can be replaced by the following code:
    helpButton.Content = ApplicationCommands.Help.Text;

    The text string is defined by each routeduicommand. WPF automatically localized the text and converts it to any language supported by WPF. This means that if the content attribute of a button is set to applicationcommands. help. text, if the UI culture of the current thread is Spanish (Spanish) rather than English (English), it will automatically display "Ayuda" instead of "help ". Although you need to provide images rather than text (possibly in a toolbar) in some contexts, you can still use this localized string elsewhere, for example, in tooltip. Of course, you still need to localize your own strings, which will be displayed on your user interface. Adjusting the text attribute of a command can reduce the number of terms you need to translate.

  • When the keybinding and mousebinding objects are added to the inputbindings set of related elements, You can bind your input gestures to a command.
    For example, to set F2 as the keyboard shortcut for executing the Help Command, add the following statement to the aboutdialog constructor:
    InputBindings.Add(new KeyBinding(ApplicationCommands.Help, new KeyGesture(Key.F2)));

    However, both F1 and F2 execute the Help Command. If you bind F1 to a special notacommand, you can change the default behavior of F1, as shown below:

    InputBindings.Add(new KeyBinding(ApplicationCommands.NotACommand, new KeyGesture(Key.F1)));

    These two statements can be replaced by the following XAML statement:

        <Window.InputBindings>        <KeyBinding Command="Help" Key="F2"/>        <KeyBinding Command="NotACommand" Key="F1"/>    </Window.InputBindings>

  • Bind built-in commands
    <StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  Orientation="Horizontal" Height="25">  <Button Command="Cut" CommandTarget="{Binding ElementName=textBox}"    Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"/>  <Button Command="Copy" CommandTarget="{Binding ElementName=textBox}"    Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"/>  <Button Command="Paste" CommandTarget="{Binding ElementName=textBox}"    Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"/>  <Button Command="Undo" CommandTarget="{Binding ElementName=textBox}"    Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"/>  <Button Command="Redo" CommandTarget="{Binding ElementName=textBox}"    Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"/>  <TextBox x:Name="textBox" Width="200"/></StackPanel>Next

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.