【发布时间】:2019-05-09 21:34:44
【问题描述】:
我的目标是重用 ListView 和我设计的 UserControl 内的其他几个控件。
为简洁起见,假设我有一个像这样的Person 类,以及它的实例列表。
public class Person
{
public string Name { get; set; }
public string City { get; set; }
}
我的MainWindow:
<Window x:Class="ReusableListView.MainWindow"
...
WindowStartupLocation="CenterScreen"
Title="MainWindow" Height="600" Width="600">
<Grid>
<local:UCListView Margin="8"
ItemsSource="{Binding PersonList, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</Window>
public partial class MainWindow : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private ObservableCollection<Person> _personList = null;
public ObservableCollection<Person> PersonList
{
get { return _personList; }
set { _personList = value; OnPropertyChanged("PersonList"); }
}
private Person _selectedPerson = null;
public Person SelectedPerson
{
get { return _selectedPerson; }
set { _selectedPerson = value; OnPropertyChanged("SelectedPerson"); }
}
public MainWindow()
{
InitializeComponent();
PersonList = GetPeople();
}
private ObservableCollection<Person> GetPeople()
{
var list = new ObservableCollection<Person>
{
new Person() { Name = "Jane", City = "NYC" },
new Person() { Name = "John", City = "LA" }
};
return list;
}
}
我想将Person 的Name 属性显示为ListView 中UserControl 内的单个项目,然后在它的右侧,我想显示所选人员的City 属性。所以我的UserControl 看起来像这样:
<UserControl x:Class="ReusableListView.UCListView"
...
x:Name="MyListViewUC"
d:DesignHeight="500" d:DesignWidth="580">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ListView Grid.Column="0" MinWidth="256" Margin="8"
DataContext="{Binding ElementName=MyListViewUC}"
ItemsSource="{Binding ItemsSource}">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock HorizontalAlignment="Left" VerticalAlignment="Center"
Width="Auto" Margin="8" Background="Pink"
Text="{Binding Name}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<TextBox Grid.Column="1" Margin="8" Background="PaleGreen"/>
</Grid>
</UserControl>
以及后面的UserControl 代码:
public partial class UCListView : UserControl
{
public UCListView()
{
InitializeComponent();
}
public object ItemsSource
{
get { return GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register("ItemsSource", typeof(object), typeof(UCListView), new PropertyMetadata(null));
}
上面的代码是从我在网上看到的大多数例子拼接在一起的,包括 SO。以下是我的问题和疑问。
- 当我运行它时,
UserControl列表中没有显示任何内容。似乎是什么问题? - 如何将
SelectedPerson属性绑定到UserContro.,以便它知道如何根据选择显示正确的City?
【问题讨论】:
-
在我看来,您不会将 MainWindow 的
DataContext分配到任何地方。 -
@jsanalytics,在我的实际程序中,我确实使用了 ViewModel。这只是为了简单地发布一个更简单的 MCVE。
-
永远不要依赖
ListView或ComboBox选择的项目,永远选择绑定属性!这种行为驱动WinForms。干得好,你没有在这里使用 MvvM 标签,因为没有。
标签: c# wpf listview user-controls itemssource