0
在WPF- ListView
控制選定的項目必須可視化一些額外的細節。 如果選擇一個項目,則需要更多的空間,然後ListView
控件提供。在ListView的選定項目內滾動
默認情況下,不能在所選項目內滾動。向下滾動, 它直接跳到下一個項目,並且不可能看到所選項目的底部部分。
任何想法如何啓用在所選項目內滾動?
以下代碼演示了該行爲。在實際的代碼所選擇的項目是比較複雜的,但舉個例子,當選擇它只是修改所選項目的大小:
XAML:
<Window x:Class="ListViewWithLargeSelectedItem.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="300" Width="300">
<Grid>
<ListView ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" HorizontalContentAlignment="Stretch">
<ListView.ItemTemplate>
<DataTemplate>
<Border x:Name="border" Padding="10" HorizontalAlignment="Stretch">
<TextBlock Text="{Binding Text}" />
</Border>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsSelected}"
Value="true">
<Setter TargetName="border" Property="Padding"
Value="40,200" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
代碼背後:
public partial class MainWindow : Window
{
private CustomItem _selectedItem;
public CustomItem SelectedItem
{
get { return _selectedItem; }
set
{
if (_selectedItem != null)
{
_selectedItem.IsSelected = false;
}
_selectedItem = value;
_selectedItem.IsSelected = true;
}
}
public List<CustomItem> Items
{
get { return (List<CustomItem>)GetValue(ItemsProperty); }
set { SetValue(ItemsProperty, value); }
}
public static readonly DependencyProperty ItemsProperty =
DependencyProperty.Register("Items", typeof(List<CustomItem>), typeof(MainWindow), new UIPropertyMetadata(null));
public MainWindow()
{
InitializeComponent();
Items = new List<CustomItem>();
for (int i = 0; i < 10; i++)
{
Items.Add(new CustomItem() { IsSelected = false, Text = "ITEM " + i });
}
DataContext = this;
}
}
public class CustomItem : INotifyPropertyChanged
{
public string Text { get; set; }
private bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set
{
if (_isSelected == value)
{
return;
}
_isSelected = value;
NotifyOfPropertyChange("IsSelected");
}
}
private void NotifyOfPropertyChange(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
正是我一直在尋找的。謝謝! – rhe1980
@ rhe1980 - 當心將此設置爲false將會禁用ListView上的UI Vritualization。 –
@RohitVats:好點!謝謝。其實我只有很少的項目,只有選定的項目需要更多的空間。 – rhe1980