我想將焦點設置TextBox
一個項目從ListView
控制選定之後,但我似乎無法得到它的注意力從我的「的SelectionChanged」事件方法FocusOnTextBox()
內。注重文本框的ListView「的SelectionChanged」事件後
由於某些原因,ListView
在選擇後始終關注。
我創建了一個Visual Studio應用程序來演示這個問題:
我怎樣才能獲得焦點返回到TextBox
從我「的SelectionChanged」事件方法內?
MainWindow.xaml:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<ListView Name="list_view1" Grid.Column="0" SelectionChanged="FocusOnTextBox">
<ListViewItem Content="1" />
<ListViewItem Content="2" />
<ListViewItem Content="3" />
</ListView>
<TextBox Name="text_box1" Grid.Column="1" Text="When a selection is chosen from the left hand side ListView, I want THIS word to be selected and for the focus to change to this text box - this will show the selection to the user.

However, right now it doesn't seem to work, the focus remains on the ListView regardless of it being set to Focus() in the FocusOnTextBox() method, which is fired on the 'SelectionChanged' event." TextWrapping="Wrap" />
</Grid>
</Window>
MainWindow.xaml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// Test that the selection of the word THIS and the Focus() works
text_box1.SelectionStart = 68;
text_box1.SelectionLength = 4;
text_box1.Focus();
}
private void FocusOnTextBox(object sender, SelectionChangedEventArgs e)
{
MessageBox.Show("FocusOnTextBox fired on selection with list view");
text_box1.SelectionStart = 68;
text_box1.SelectionLength = 4;
text_box1.Focus();
}
}
}
+1不錯!這正是它,我只是在本地擺弄它,無法讓它把注意力放在SelectionChanged事件上;也沒有辦法取消事件並且沒有事件預覽;您的解決方案非常優雅,因爲您可以在用戶單擊以更改選擇時將焦點更改附加到內部列表視圖事件觸發順序的末尾。當我擺弄這個時,我檢查了你的解決方案,它確實工作得非常好! – 2013-03-06 19:00:54
謝謝@DavidKhaykin。我已經在WPF中與Focus進行了很多搏鬥,並且它可以變得非常多毛。即使知道爲什麼在這種情況下,我正在努力解釋清楚,所以希望它是有道理的。 – 2013-03-06 19:06:16