[英]WPF ListBox, the SelectedIndex is not the highlighted row
奇怪的情況,我有以下XAML:
<StackPanel>
<TextBlock>Logging here...</TextBlock>
<ListBox x:Name="LoggingListBox" ItemsSource="{Binding Log}" />
</StackPanel>
我的源代碼是ObservableCollection<string>
中的5行文本,我選擇了第四行:
LoggingListBox.SelectedIndex = 3;
但顯示如下:
如您所見,第三項確實有邊框,但是為什么第一行突出顯示?
有人知道發生了什么事嗎?
更新1/17/17:我已經制作了一個較小的演示版本的問題。
1)新的WPF項目
2)MainWindow.xaml:
<Window x:Class="ListBoxSelectionTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow">
<StackPanel>
<TextBlock>Logging here...</TextBlock>
<ListBox x:Name="LoggingListBox" ItemsSource="{Binding Log}" />
</StackPanel>
</Window>
3)后面的代碼:
public partial class MainWindow
{
public ObservableCollection<string> Log { get; set; }
public MainWindow()
{
InitializeComponent();
DataContext = this;
Log = new ObservableCollection<string>();
Log.CollectionChanged += (o, e) => LoggingListBox.SelectedItem = Log.Last();
Log.Add("Adding instrument: Unknown:#22");
Log.Add("Adding instrument: Unknown:#22");
Log.Add("Adding instrument: Unknown:#22");
Log.Add("Adding instrument: Unknown:#22");
Log.Add("Adding instrument: Unknown:#22");
}
}
4:運行程序:啟動時如下所示:
5:按下TAB按鈕(將焦點設置到列表框),現在看起來像:
我懷疑我以某種方式設置了WPF真正想要的錯誤順序。
編輯后,您的情況更清楚了。
首先,請注意,對示例進行小的測試更改可以解決此問題:
Log.Add("Adding instrument: Unknown:#22");
Log.Add("Adding instrument: Unknown:#23");
Log.Add("Adding instrument: Unknown:#24");
Log.Add("Adding instrument: Unknown:#25");
Log.Add("Adding instrument: Unknown:#26");
現在每個字符串都不同。 因此,第一行是灰色\\藍色的原因是因為ListBox基本上不能消除它們。
但是,為什么我們要點虛線框呢? 好吧,這是因為它是由另一種機制-FocusVisualStyle繪制的。 並且它似乎可以正確跟蹤選定的視覺元素。
對於這種情況有不同的可能解決方案,但是為什么不只將選擇邏輯移到索引上並完成呢?
LoggingListBox.Loaded += (o, e) =>
{
Log.CollectionChanged += (oo, ee) => SelectLastEntry();
SelectLastEntry();
};
...
private void SelectLastEntry()
{
LoggingListBox.SelectedIndex = LoggingListBox.Items.Count - 1;
}
看起來像您選擇的項目,但未突出顯示。 聚焦時,您可以嘗試突出顯示為青色。
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Cyan"/>
不聚焦時呈灰色。
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Gray" />
ListBox
旨在處理多個選擇,並且突出顯示是單獨的情況。 您還需要將其滾動到視圖中,以將突出顯示更改為選定的
LoggingListBox.ScrollIntoView(LoggingListBox.Items[3]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.