我正在开发一个触摸屏应用程序,当光标聚焦在任何文本框上时,我需要打开触摸屏键盘。我使用以下代码来调用我在视图模型中的命令..
<i:Interaction.Triggers>
<i:EventTrigger EventName="GotFocus">
<i:InvokeCommandAction Command="{Binding openKeyboard}" />
</i:EventTrigger>
</i:Interaction.Triggers>
当我在每个文本框上写的时候工作正常...让我有单个形式的多个文本框,有没有办法一般写它,应该适用于我的表单(或)应用程序的所有文本框?
先谢谢
答案 0 :(得分:2)
我喜欢使用附加行为。以下是我获得焦点时在文本框中选择值的示例。这样,您可以将此行为应用于任何文本框。附加行为的一个好处是许多属性/事件都在UIElement级别,因此您可以重用多个控件中的某些行为。无论如何,这是我的例子:
<强>行为强>
public class SelectAllOnFocusedBehavior
{
private static bool GetSelectAllOnFocused(TextBox textBox)
{
return (bool) textBox.GetValue(SelectAllOnFocusedProperty);
}
public static void SetSelectAllOnFocused(
TextBox textBox, bool value)
{
textBox.SetValue(SelectAllOnFocusedProperty, value);
}
public static readonly DependencyProperty SelectAllOnFocusedProperty =
DependencyProperty.RegisterAttached(
"SelectAllOnFocused",
typeof (bool),
typeof (SelectAllOnFocusedBehavior),
new UIPropertyMetadata(false, OnSelectAllOnFocusedChanged));
private static void OnSelectAllOnFocusedChanged(
DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
TextBox item = depObj as TextBox;
if (item == null)
return;
if (e.NewValue is bool == false)
return;
if ((bool) e.NewValue)
{
item.PreviewMouseLeftButtonDown += item_IgnoreLeftMouseDown;
item.GotFocus+=item_GotFocus;
}
else
{
//remove EventsHere
item.PreviewMouseLeftButtonDown -= item_IgnoreLeftMouseDown;
item.GotFocus -= item_GotFocus;
}
}
static void item_IgnoreLeftMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
// Find the TextBox
DependencyObject parent = e.OriginalSource as UIElement;
while (parent != null && !(parent is TextBox))
parent = VisualTreeHelper.GetParent(parent);
if (parent != null)
{
var textBox = (TextBox)parent;
if (!textBox.IsKeyboardFocusWithin)
{
// If the text box is not yet focussed, give it the focus and
// stop further processing of this click event.
textBox.Focus();
e.Handled = true;
}
}
}
static void item_GotFocus(object sender, RoutedEventArgs e)
{
var item = e.OriginalSource as TextBox;
if (item != null)
item.SelectAll();
}
//EventHandler Here
}
对应的wpf
<TextBox x:Name="blahblah"
cmds:SelectAllOnFocusedBehavior.SelectAllOnFocused="True"
cmds:NextTabItemOnEnterBehavior.NextTabItemOnEnter="True"
Height="20" Width="75"
答案 1 :(得分:0)
如果您正在使用Caliburn,则可以执行以下操作在ViewModel上触发某些事情:
<i:Interaction.Triggers>
<i:EventTrigger EventName="GotFocus">
<cal:ActionMessage MethodName="openKeyboard" />
</i:EventTrigger>
</i:Interaction.Triggers>
然后在ViewModel上创建一个与 MethodName 同名的方法:
public void openKeyboard()
{
// Do your stuff
}
希望对您有帮助。