我使用一个包含三个项的ListView创建了一个极简样例,并在它旁边创建了一个显示所选ListViewItem的contentControl。令我困惑的是,当我选择一个项目时,它会正确地显示在ContentControl上,但在ListView中却变得如此小,就像它正在消失一样。有人能解释一下这里发生了什么吗?
网格中具有ListView和ContentControl的ContentControl。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。它会显示在右边的contentcontrol上,但是ListView现在看起来很奇怪。我也可以在其他ListViewItems上重复这一点。

这是在单击TB2,最后单击TB3之后
发布于 2020-10-09 16:43:01
您的问题是控件只能在ui中出现一次。
你在用代码构建控件。
当您选择一个,它是从您选择它的地方,并移动到您绑定它的地方。
不要在代码中构建控件。
使用mvvm。
构建数据(视图模型)并绑定到ui。
将数据转换为控件的数据板。
https://stackoverflow.com/questions/64283984
复制相似问题