How to make a TextBox with a Button inside in WPF?

39,061

Solution 1

If you want something like a combobox or a date time picker you should create a new control, inside this new control place a text box and a button side by side inside a frame that looks like the frame of a textbox - then restyle the textbox so it doesn't have a frame.

putting a button inside a rich edit is great if you want to put a button inside a "document" but not a good substitute for a combobox.

See the ComboBox control template MSDN

Solution 2

You may find this link helps: http://msdn.microsoft.com/en-us/library/ms752068(VS.85).aspx.

"The ControlTemplate for a TextBox must contain exactly one element that is tagged as the content host element; this element will be used to render the contents of the TextBox. To tag an element as the content host, assign it the special name PART_ContentHost. The content host element must be either a ScrollViewer or an AdornerDecorator. The content host element may not host any child elements."

Solution 3

I created a textbox control and added this It seems to work, but not the ideal situation cos it recreates another textbox.

<TextBox.Template>
 <ControlTemplate>
        <Grid>
            <Grid.ColumnDefinitions></Grid.ColumnDefinitions>
            <TextBox Grid.Column="0"></TextBox>
            <Button HorizontalAlignment="Right" Width="25" Grid.Column="1">
            </Button>
        </Grid>         
    </ControlTemplate>
</TextBox.Template>

Solution 4

Simple solution


You can fake the fact that the button is in the TextBox by putting the Button over the TextBox. Don’t forget to put padding on your TextBox to avoid text going behind the Button.

Code example with StackPanel :

<StackPanel Orientation="Horizontal">
    <TextBox Width="200" Padding="0,0,30,0" Height="30" FontSize="16"/>
    <Button Width="20" Height="20" Margin="-30,0,0,0"/>
</StackPanel>

Code example with Grid :

<Grid>
    <TextBox Width="200" Padding="0,0,30,0" Height="30" FontSize="16"/>
    <Button Width="20" Height="20" HorizontalAlignment="Right" Margin="0,0,5,0"/>
</Grid>

Result :

enter image description here

Share:
39,061
Max Galkin
Author by

Max Galkin

Blog: http://yacoder.guru/blog/ Twitter: @yacoder My CV: http://careers.stackoverflow.com/yacoder

Updated on May 28, 2021

Comments

  • Max Galkin
    Max Galkin about 3 years

    I'd like to make a TextBox with a Button inside, something like a DatePicker, but not exactly. Or can it be a ComboBox inside the TextBox, so you can switch the mode of the TextBox.

    Can you help me?