我刚开始学习有关WPF的课程,对于与数据绑定相关的一些领域感到有些困惑。我的语法没有问题,但很可能犯了一些新手错误,因此我有几个问题。
我做了一个简单的屏幕,其中有2个文本框,当我点击按钮时,这两个项目将添加到一个ListBox中。
在XAML
的Window标签内引用People类。
xmlns:classes="clr-namespace:WPF_Course.Classes"
新增了一个窗口资源
<Window.Resources>
<classes:People x:Key="people"/>
</Window.Resources>
以下是我如何声明ListBox:
<ListBox DataContext="{Binding Source={StaticResource people}}"
ItemsSource="{Binding Persons}"
x:Name="PersonListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<StackPanel>
<TextBlock Text="{Binding FullName}"/>
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
所以,我已经向我的ListBox添加了一个
DataContext
,在那里绑定到我的people资源,并且我添加了一个ItemSource
,其中查找我的People
中的属性。这是我的类。
public class People : ObservableCollection<Person>
{
public ObservableCollection<Person> Persons { get { return persons; } set { persons = value; } }
private ObservableCollection<Person> persons = new ObservableCollection<Person>();
public People()
{
for (int i = 0; i < 1; i++)
{
// implicitly I add one item just for messing around with the constructor
Persons.Add(new Person()
{
Name = "Dummy",
LastName = "Dummy",
Age = 15
});
}
}
}
根据我目前的工作,我有以下问题:
1)(它们有相同的效果,但是它们背后的推理不同是什么区别?)的区别是什么?
ItemsSource = "{Binding Persons}"
并且
ItemsSource = "{Binding Path = Persons }"
同时,如果我将
ItemSource = "{Binding}"
留空,那么我是不是实例化了一个 People 实例,因此所有的逻辑都从该类的构造函数中处理?我已经试过了,似乎确实如此,但我不确定。2)在我的 People 类中,我已经实现了
ObservableCollection<Person>
(其中 Person 也是一个类)。最初,我是从构造函数本身对列表进行静态添加的,并且没有在类内定义属性(ObservableCollection<person> type
类型的属性),因此需要它(接口的实现),但现在使用属性,我真的需要它吗?所以我的问题是:如果我的类唯一的目的是仅从构造函数中加载其集合中的内容(而不是来自外部类,因此需要某种属性),那么将我的类与
ObservableCollection<myClass>
结合使用是最佳实践,还是像我所做的那样定义相同类型的属性?(用于从外部类访问)非常抱歉,我的问题听起来有些愚蠢,我正在寻求验证,因为我最近才开始使用 wpf。
谢谢
ObservableCollection<Person> ppl;
public MainWindow()
{
InitializeComponent();
person = new Person();
stackPanelPerson.DataContext = person;
people = new People();
ppl = people.Persons;
PersonListBox.ItemsSource = ppl;
}
一开始我是这样做的。
ppl.Add(new Person() { Name = boxFirstName.Text, LastName = boxLastName.Text, Age = Int32.Parse(boxAge.Text) });
后来我意识到我在我的Person类(INotifyPropertyChanged)上使用了数据绑定,所以我将其更改为:
ppl.Add(new Person() { Name = person.Name, LastName = person.LastName, Age = person.Age});
感谢大家的回复!再次致以感谢!祝你们有美好的一天!