为了账号安全,请及时绑定邮箱和手机立即绑定

WPF绑定同一类的两个对象

WPF绑定同一类的两个对象

C#
哆啦的时光机 2022-11-13 13:44:20
我有一堂课: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。
查看完整描述

1 回答

?
HUX布斯

TA贡献1876条经验 获得超6个赞

请首先像这样设置数据上下文。


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

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


DataContext =  new           

{

  Person1 = person1,

  Person2 = person2 

};

在像这样设计侧绑定数据之后。


<Grid>

    <TextBox Text="{Binding Person1.Name,Mode=TwoWay, 

                                  UpdateSourceTrigger=PropertyChanged}"/>

</Grid>


<Grid>

    <TextBox Text="{Binding Person2.Name,Mode=TwoWay, 

                                  UpdateSourceTrigger=PropertyChanged}"/>

</Grid>

或(您只能像这样在设计方面进行更改)


<Grid DataContext="{Binding person1}">

    <TextBox Text="{Binding Name,Mode=TwoWay, 

                                      UpdateSourceTrigger=PropertyChanged}"/>

</Grid>


<Grid DataContext="{Binding person2}">

      <TextBox Text="{Binding Name,Mode=TwoWay, 

                                      UpdateSourceTrigger=PropertyChanged}"/>

</Grid>


查看完整回答
反对 回复 2022-11-13
  • 1 回答
  • 0 关注
  • 98 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信