Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

wpf

textbox

xaml

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?

like image 564
Max Galkin Avatar asked Sep 10 '09 08:09

Max Galkin


4 Answers

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

like image 89
Nir Avatar answered Oct 15 '22 17:10

Nir


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>
like image 31
Tim Avatar answered Oct 15 '22 19:10

Tim


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."

like image 5
Xiaoqing Avatar answered Oct 15 '22 18:10

Xiaoqing


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

like image 3
Xaalek Avatar answered Oct 15 '22 17:10

Xaalek