开发者

WPF: How to change button content (text) with a double click at runtime

I have a button in WPF, I want to change the text when I double click on it, that is I want the cursor to appear and type the text that is to be shown as the content (similar behavior as when pressing F2 on a desktop shortcut).

I guess I could detect a double click and then show a textbox with a transparent background, that will get me the cursor, type the text in this new textbox, set it to the buttons content and delete the textbox, but that doesn't seem the right way to do it.


I guess what I had in mind, is that I am developing a diagramming tool using shapes. Since shape doesn't derive from C开发者_如何学ContentControl I cannot put a text box inside it, and I want to simulate this behavior. I was thinking of making a custom control but that might be too much work for this, and am not quite familiar with this topic yet. I guess another approach would be to use an adorner (maybe a border) and since it derives from contentcontrol I can do the same thing as joe suggested. any ideas?

Another thing I could do would be to put the shape in a grid, and then put the textbox on top of the shape, but I am not sure how would that be as a design principle, and also I don't know if the hit testing would only be on the shape or the grid.


Since this is WPF, you can put a TextBox inside your Button with no trouble. If you don't want the textbox to have a border and white background -- i.e., if you want it to look like you're just typing directly into the button -- then you could remove them by setting BorderWidth to 0 and Background to Transparent.

What you probably want to do is have your Button's Content be a Grid that contains both the normal content (probably a TextBlock) and the TextBox, with the TextBox initially hidden (Visibility = Collapsed). Then when you get the double-click event, you would hide the TextBlock and show the TextBox.

<Button>
    <Grid>
        <TextBlock Name="buttonText">Double-click to rename me</TextBlock>
        <TextBox Name="buttonEdit" Visibility="Collapsed" MinWidth="100"/>
    </Grid>
</Button>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜