我有一个包含文本框和组合框的StackPanel。
当我将焦点设置在文本框内(不是第一个文本框),StackPanel的内容会“跳动”并回到顶部。
以下是代码。我已经研究过这个问题并尝试了找到的解决方法(但没有成功)。
我想要防止“跳动”发生。
请运行下面的代码。 滚动垂直滚动条,直到看到:
Name Three <<Text Box
(No Selection) ComboBox \/
Name Four <<Text Box
(No Selection) ComboBox \/
现在把光标放在“Name Four”文本框里......然后它会“跳”到顶部。 (现在你看不到 Three 和 Four,你看到的是 Four 和 Five。)
我的 StackPanel 在实际使用中比这个复杂得多,这让我的最终用户感到疯狂。
谢谢。
MainWindow.xaml
<Window x:Class="ListBoxControlSample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="160" Width="250">
<Grid Margin="10">
<ListBox ItemsSource="{Binding Models}" SelectionMode="Single" RequestBringIntoView="FrameworkElement_OnRequestBringIntoView" SelectionChanged="Selector_OnSelectionChanged" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBox Text="{Binding Name}"/>
<ComboBox VerticalContentAlignment="Top" VerticalAlignment="Top" Grid.Column="1" ItemsSource="{Binding Options}" >
</ComboBox>
<TextBlock Text="{Binding Title}"></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</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 ListBoxControlSample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
private IList<Model> _models;
public IList<Model> Models
{
get
{
return _models ?? (_models = new List<Model>
{
new Model{ Name = "Name One", Title = "Title One"},
new Model{ Name = "Name Two", Title = "Title Two"},
new Model{ Name = "Name Three", Title = "Title Three"},
new Model{ Name = "Name Four", Title = "Title Four"},
new Model{ Name = "Name Five", Title = "Title Five"},
new Model{ Name = "Name Six", Title = "Title Six"},
new Model{ Name = "Name Seven", Title = "Title Seven"}
});
}
}
private void FrameworkElement_OnRequestBringIntoView(object sender, RequestBringIntoViewEventArgs e)
{
e.Handled = true;
}
private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
//throw new NotImplementedException();
}
private void Selector_OnSelected(object sender, RoutedEventArgs e)
{
//throw new NotImplementedException();
}
}
public class Model
{
public string Name { get; set; }
public string Title { get; set; }
private IList<string> _options;
public IList<string> Options
{
get
{
return _options ?? (_options = new List<string>
{
"left",
"right",
"both"
});
}
}
}
}
我发现并尝试过的方法(以防止跳跃)
<DataTemplate>
<StackPanel ScrollViewer.CanContentScroll="False">