WPF绑定同一类的两个对象

我有一堂课:


public class Person {

    public string Name { set; get; }

}

我从那个班级实例化了 2 个人:


Person person1 = new Person() { Name="Test1" };

Person person2 = new Person() { Name="Test2" };

在我的 Window.xaml 中,我有两个文本框,我想将它们与两个人对象绑定


<Grid>

    <TextBox />

</Grid>


<Grid>

    <TextBox/>

</Grid>

但我是 WPF 的新手,不知道该怎么做。


我试过了


<Grid DataContext="{Binding person1}">

    <TextBox Text="Binding Name"/>

</Grid>


<Grid DataContext="{Binding person2}">

    <TextBox Text="Binding Name"/>

</Grid>

没用。试过了


<Grid>

    <TextBox Text="Binding person1.Name"/>

</Grid>


<Grid>

    <TextBox Text="Binding person2.Name"/>

</Grid>

没用。


我可以绑定一个人在 Window1.cs 中设置 DataContext


但我不能(或不知道如何)将 2 人设置为 Window1 中的 DataContex。


哆啦的时光机
浏览 99回答 1
1回答

HUX布斯

请首先像这样设置数据上下文。Person person1 = new Person() { Name="Test1" };Person person2 = new Person() { Name="Test2" };DataContext =&nbsp; new&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; Person1 = person1,&nbsp; Person2 = person2&nbsp;};在像这样设计侧绑定数据之后。<Grid>&nbsp; &nbsp; <TextBox Text="{Binding Person1.Name,Mode=TwoWay,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; UpdateSourceTrigger=PropertyChanged}"/></Grid><Grid>&nbsp; &nbsp; <TextBox Text="{Binding Person2.Name,Mode=TwoWay,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; UpdateSourceTrigger=PropertyChanged}"/></Grid>或(您只能像这样在设计方面进行更改)<Grid DataContext="{Binding person1}">&nbsp; &nbsp; <TextBox Text="{Binding Name,Mode=TwoWay,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; UpdateSourceTrigger=PropertyChanged}"/></Grid><Grid DataContext="{Binding person2}">&nbsp; &nbsp; &nbsp; <TextBox Text="{Binding Name,Mode=TwoWay,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; UpdateSourceTrigger=PropertyChanged}"/></Grid>
打开App,查看更多内容
随时随地看视频慕课网APP