如何使用Caliburn.Micro选择TextBox中的所有文本?

时间:2014-10-30 11:42:16

标签: c# wpf caliburn.micro

在我的WPF应用程序中,我使用Caliburn.Micro绑定View和ViewModel。

在我的视图中,我有StackPanel文本框

<StackPanel>
    <TextBox x:Name="Ctx_A" />
    <TextBox x:Name="Ctx_B" />
    <TextBox x:Name="Ctx_C" />
    <TextBox x:Name="Ctx_D" />
</StackPanel>

现在我想在关注TextBox后选择所有文本。在我的ViewModel中,我编写方法TextBoxGotFocus

public void TextBoxGotFocus(object sender)
{
  var tb = sender as TextBox;
  if (tb != null)
  {
    tb.SelectAll();
  }
}

接下来我回到我的视图并写下类似的内容:

<StackPanel>
    <TextBox x:Name="Ctx_A" cal:Message.Attach=" [Event GotFocus]=[Action TextBoxGotFocus($source)]"/>
    <TextBox x:Name="Ctx_B" cal:Message.Attach=" [Event GotFocus]=[Action TextBoxGotFocus($source)]"/>
    <TextBox x:Name="Ctx_C" cal:Message.Attach=" [Event GotFocus]=[Action TextBoxGotFocus($source)]"/>
    <TextBox x:Name="Ctx_D" cal:Message.Attach=" [Event GotFocus]=[Action TextBoxGotFocus($source)]"/>
</StackPanel>

是否有可能将此方法附加到StackPanel而不是TextBox?

2 个答案:

答案 0 :(得分:1)

我会从您的视图模型中删除TextBoxGotFocus()方法,因为它会模糊视图和视图模型之间的线条。视图模型不应该使用其中的任何WPF控件。相反,我能想到的最简单的方法是创建一个继承自TextBox的类,然后将事件附加到该类:

public class AutofocusTextBox : TextBox
{
    public AutofocusTextBox()
    {
        GotFocus += (sender, e) => SelectAll();
    }
}

然后在您的XAML中,您可以像这样使用它:

<local:AutofocusTextBox ... />

这将使您的XAML更加清洁

答案 1 :(得分:0)

所有功劳归给WPF博士... Source

在abcView.xaml中

<TextBox    Text="{Binding Amount}" 
            MinWidth="100" 
            cal:Message.Attach="[Event GotFocus] = [Action GotFocusMethod($source)];
            [Event PreviewMouseLeftButtonDown] = [Action SelectivelyIgnoreMouseButton($source, $eventArgs)]" />

在abcViewModel.cs

    // called by ui... used to highlight a textbox on focus
    public void GotFocusMethod(object source)
    {
        var based = source as TextBox;
        based.SelectAll();
    } // close gotfocusmethod

    // called by ui... used to highlight a textbox on focus
    public void SelectivelyIgnoreMouseButton(object sender, MouseButtonEventArgs eve)
    {
        TextBox tb = (sender as TextBox);

        if (tb != null)
        {
            if (!tb.IsKeyboardFocusWithin)
            {
                eve.Handled = true;

                tb.Focus();
            }
        }
    } // close selectivelyignoremousebutton()