我有一个项目控制给我带来了问题。它有一个datatemplate,其中包含一个绑定到代码隐藏中的属性的文本框。当我按Enter键时,一个新元素将插入到属性中。发生这种情况后,数据模板中的项的焦点应向下移动项控件中的一个项(以编程方式完成)。但是,它没有,而是由两个元素转换。我在控件中放置了一个递归的可视化树阅读器方法,试图弄清楚发生了什么,看起来缺少一个可视化元素。但是,我不知道是什么导致了这个问题,也不知道如何解决它。任何帮助都将不胜感激。谢谢!
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Collections.ObjectModel;
using System.IO;
namespace FunWithListBox.View
{
/// <summary>
/// Interaction logic for EntryListView.xaml
/// </summary>
public partial class EntryListView : UserControl
{
private ObservableCollection<string> itemList;
public ObservableCollection<string> ItemList
{
get { return itemList; }
set { itemList = value; }
}
public EntryListView()
{
InitializeComponent();
itemList = new ObservableCollection<string>();
itemList.Add("First string in the list.");
itemList.Add("Second string in the list.");
itemList.Add("Third string in the list.");
itemList.Add("Fourth string in the list.");
itemList.Add("Fifth string in the list.");
DataContext = this;
}
private void UserControl_KeyDown(object sender, KeyEventArgs e)
{
Type focType = Keyboard.FocusedElement.GetType();
if (focType == typeof(TextBox))
{
if (e.Key == Key.Return)
{
TextBox tbxWithFocus = Keyboard.FocusedElement as TextBox;
int index = itemList.IndexOf(tbxWithFocus.DataContext as string);
string strToCursor = tbxWithFocus.Text.Substring(0, tbxWithFocus.CaretIndex);
string strPastCursor = tbxWithFocus.Text.Substring(tbxWithFocus.CaretIndex);
itemList[index] = strToCursor;
if (index == itemList.Count - 1)
itemList.Add(strPastCursor);
else
itemList.Insert(index + 1, strPastCursor);
TextWriter tw = new StreamWriter("sampleVisualTree.txt");
tw.Write(getVisualTree(myItemsControl, 2));
tw.Close();
tbxWithFocus.MoveFocus(new TraversalRequest(FocusNavigationDirection.Down));
}
}
}
private string getVisualTree(DependencyObject dpo, int depth)
{
string treeString;
treeString = String.Empty.PadRight(depth, ' ') + dpo.ToString();
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dpo); i++)
treeString +=
Environment.NewLine +
getVisualTree(VisualTreeHelper.GetChild(dpo, i), depth + 2);
return treeString;
}
}
}
此外,以下是XAML:
<UserControl x:Class="FunWithListBox.View.EntryListView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300"
KeyDown="UserControl_KeyDown">
<Grid>
<ItemsControl ItemsSource="{Binding Path=ItemList}"
x:Name="myItemsControl">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged,
Path=.}"
BorderThickness="0" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</UserControl>
干杯,
安得烈