简体   繁体   中英

How can I apply a custom TextBox style to built-in controls?

Background:

In a standard WPF application, right clicking on a TextBox displays a ContextMenu with three commands: Cut, Copy, and Paste. My desire is to add a Select All command to all TextBox ContextMenus in my application.

Problem:

My standard approach is to create a Style that targets TextBox and supplies the new ContextMenu. That way, all TextBox controls inherit the style and pick up the change.

The trouble is that my style isn't inherited by controls that contain TextBoxes. For instance, when editing a DataGridTextColumn cell, I know a TextBox is used but it doesn't inherit my style. The same goes for some 3rd party controls used by my application.

Question:

Is there some other way to have controls, like the DataGridTextColumn's cell, pick up my style changes, or am I stuck altering their templates?

Addendum:

This is the style:

<Style 
    TargetType="{x:Type TextBox}"
    BasedOn="{StaticResource {x:Type TextBox}}"
    >
    <Setter
        Property="ContextMenu"
        >
        <Setter.Value>
            <ContextMenu>
                <MenuItem
                    Header="Cu_t"
                    Command="ApplicationCommands.Cut"
                    InputGestureText="Ctrl+X"
                    />
                <MenuItem
                    Header="_Copy"
                    Command="ApplicationCommands.Copy"
                    InputGestureText="Ctrl+C"
                    />
                <MenuItem
                    Header="_Paste"
                    Command="ApplicationCommands.Paste"
                    InputGestureText="Ctrl+V"
                    />
                <Separator
                    />
                <MenuItem
                    Header="Select _All"
                    Command="ApplicationCommands.SelectAll"
                    InputGestureText="Ctrl+A"
                    />
            </ContextMenu>
        </Setter.Value>
    </Setter>
</Style>

your textbox style will be reflected to textboxes who dont have any style applied. So if you have any third party textbox and it has already a style applied with key. your style will fail. you may need to use expression blend to open the the control template and change style or understand how the textbox style applied there.

cheers..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM