我有一个标签显示一些内容。当用户双击标签时,应该允许用户更改内容。
我做了一些研究,发现实现这种简单的效果通常非常复杂。 http://ludovic.chabant.com/devblog/2010/10/05/making-wpf-controls-double-clickable/
但我需要的是双击时可以编辑的标签(或文本框)。有更简单的方法吗?
谢谢!
答案 0 :(得分:3)
我认为您必须处理一些事件(无法在XAML代码中设置所有事件):
//Initially set Focusable to false
textBox1.Focusable = false;
textBox1.Cursor = Cursors.Arrow;
//FocusableChanged event handler for your textBox1
private void textBox1_FocusableChanged(object sender,
DependencyPropertyChangedEventArgs e){
textBox1.Cursor = textBox1.Focusable ? Cursors.IBeam : Cursors.Arrow;
}
//MouseDoubleClick event handler for your textBox1
private void textBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e){
textBox1.Focusable = true;
textBox1.Focus();
textBox1.CaretIndex = textBox1.Text.Length;
}
//LostFocus event handler for your textBox1
private void textBox1_LostFocus(object sender, RoutedEventArgs e){
textBox1.Focusable = false;
}
答案 1 :(得分:1)
您可以创建textbox
之类的:
TextBox editLbl = new TextBox();
//add it to the controls list to display it
并将标签的所有属性设置为textbox
,如location
,size
等。
设置keydown
事件,然后按Enter键,隐藏textbox
并将值设置为标签。
您还可以将background color
主题设置为与表单窗口相同,就像您正在编辑标签一样。
答案 2 :(得分:0)
如果您使用非MVVM,则可以执行以下操作
答案 3 :(得分:0)
这种方式对我来说很好。修复了该线程中的先前答案代码(双击后立即触发LostFocus)。
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;
public class DoubleClickTextBoxBehaviour : Behavior<TextBox>
{
private long _timestamp;
protected override void OnAttached()
{
AssociatedObject.Focusable = false;
AssociatedObject.Cursor = Cursors.Arrow;
AssociatedObject.MouseDoubleClick += AssociatedObjectOnMouseDoubleClick;
AssociatedObject.LostFocus += AssociatedObjectOnLostFocus;
}
private void AssociatedObjectOnMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton != MouseButton.Left)
return;
if (AssociatedObject.Focusable)
return;//fix an issue of selecting all text on double click
AssociatedObject.Cursor = Cursors.IBeam;
AssociatedObject.Focusable = true;
AssociatedObject.Focus();
AssociatedObject.CaretIndex = AssociatedObject.Text.Length;
_timestamp = Stopwatch.GetTimestamp();
}
private void AssociatedObjectOnLostFocus(object sender, RoutedEventArgs e)
{
var delta = Stopwatch.GetTimestamp() - _timestamp;
var timesp = new TimeSpan(delta);
if (timesp.TotalSeconds < 1)
return;
AssociatedObject.Cursor = Cursors.Arrow;
AssociatedObject.Focusable = false;
}
}
将其附加到文本框:
<TextBox Text="{Binding MyText}">
<i:Interaction.Behaviors>
<behaviours:DoubleClickTextBoxBehaviour />
</i:Interaction.Behaviors>
</TextBox>
如果出错