【发布时间】:2018-11-22 15:12:21
【问题描述】:
我(C# 和 WPF 中的新手)试图绑定来自更多源(类属性)的数据,但我对不同的指南和建议感到有些困惑。我想在userList 中动态添加Users,并同时显示最后一个插入和整个列表。这是在源代码的不同位置完成的,但很简单,就像在我的示例的构造器中一样。我应该如何以及在哪里为这三个元素(myName、myTitle 和myUserList)设置绑定和数据上下文以反映主类属性的变化?我应该调用每个时间函数来更新绑定目标,还是在编辑属性后设置this.datacontext?或者我应该绑定到某个返回我需要的值的函数(如果可能的话)?我对绑定到对象和数据上下文等的属性有点迷失了。这是我所拥有的一个例子:
<Window x:Name="Window" x:Class="WpfTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfTest">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="200"/>
</Grid.ColumnDefinitions>
<StackPanel>
<TextBox x:Name="myName" Text="" Grid.Column="1"/>
<TextBox x:Name="myTitle" Text="" Grid.Column="0"/>
</StackPanel>
<ListBox x:Name="myUserList">
</ListBox>
</Grid>
</Window>
和
public partial class MainWindow : Window {
public User myUser;
public Dictionary<int,User> userList= new Dictionary<int, User>();
public object SubWindow { get; private set; }
public MainWindow() {
newUser = new User();
newUser.Title = "John Doe";
newUser.Name = "Dr.";
this.userList.Add(index,newUser);
this.myUser=newUser;
InitializeComponent();
}
}
和
public class User
{
public String Name { get; set; }
public String Title { get; set; }
}
感谢您的建议。
【问题讨论】:
-
当您从代码隐藏更新 UI 元素时,您错过了数据绑定的含义 - 这是不是数据绑定! ;-) 在这里阅读一下,看看它是如何工作的:wpf-tutorial.com/data-binding/introduction
标签: c# wpf data-binding datacontext