【发布时间】:2020-10-09 16:33:34
【问题描述】:
我创建了一个简约示例,其中使用了一个 ListView,其中包含三个项目,旁边的一个 contentControl 显示选定的 ListViewItem。令我困惑的是,当我选择一个项目时,它在 ContentControl 上正确显示,但在 ListView 中变得如此之小,就像它正在消失一样。谁能解释一下这里发生了什么?
在网格中具有 ListView 和 ContentControl 的 MainWindow。 ContentControl.Content 绑定到 ListView 的选定项。
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ListView ItemsSource="{Binding ListViewItems}" SelectedItem="{Binding SelectedListViewItem}"/>
<ContentControl Grid.Column="1" Content="{Binding SelectedListViewItem}"/>
</Grid>
</Window>
MainWindow 的 DataContext 设置为 MainWindowViewModel
using System.Windows;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
}
}
MainWindowViewModel 实现 INotifyPropertyChanged 并保存 ListViewItems 以及 SelectedListViewItem。
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Controls;
public class MainWindowViewModel : INotifyPropertyChanged
{
public MainWindowViewModel()
{
ListViewItems = new ObservableCollection<Control>()
{
new TextBox(){ Text = "TB1", IsReadOnly = true },
new TextBox(){ Text = "TB2", IsReadOnly = true },
new TextBox(){ Text = "TB3", IsReadOnly = true },
};
}
private ObservableCollection<Control> _listViewItems;
private Control _selectedListViewItem;
public ObservableCollection<Control> ListViewItems
{
get
{
return _listViewItems;
}
set
{
if (SetProperty(ref _listViewItems, value))
{
}
}
}
public Control SelectedListViewItem
{
get
{
return _selectedListViewItem;
}
set
{
if (SetProperty(ref _selectedListViewItem, value))
{
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected virtual bool SetProperty<T>(ref T backingField, T newValue, [CallerMemberName] string propertyName = null)
{
var ret = false;
if (!EqualityComparer<T>.Default.Equals(backingField, newValue))
{
backingField = newValue;
OnPropertyChanged(propertyName);
ret = true;
}
return ret;
}
}
我知道 ViewModel 不应包含对任何视图的任何引用。然而,从最小的样本来看,这是必需的。我的问题是为什么 ListViewItems “消失”。
我点击了第一个 ListViewItem,TB1。它显示在右侧的内容控件上,但 ListView 现在看起来很奇怪。我也可以对其他 ListViewItems 重复此操作。
这是在点击 TB2 之后,最后点击 TB3
【问题讨论】: