【发布时间】:2016-11-14 01:20:42
【问题描述】:
最近有人告诉我,在使用 WPF 和数据绑定时,最好不要命名任何字段,而只是将它们与其他类中的属性相关联。我现在的问题是如何添加来自 3 个文本框(用户输入)的数据,将绑定的信息保存到模型中,然后将帐户信息发布到侧面的列表框中。我需要将数据添加到我的模型中。我的 main.xaml 代码如下:
<ListBox ItemsSource="{Binding Path=Files}" SelectedItem="{BindingPath=CurrentItem}" />
<TextBox Text="{Binding Path=bankaccount}"/>
<TextBox Text="{Binding Path=accountnumber}"/>
<TextBox Text="{Binding Path=accounttype}"/>
<Button Content="Save Data To Listbox" Click="Save_Click"/>
现在我将展示我的 FileModel 类,它包含我的所有属性,这些属性将来自文本框
private short _BankAccount;
private long _AccountNumber;
private char _AccountType;
public short bankaccount{ get { return _BankAccount;} set {_BankAccount= value; Notify("bankaccount"); } }
public long accountnumber{ get { return _AccountNumber;} set {_AccountNumber= value; Notify("accountnumber"); } }
public char accounttype{ get { return _AccountType;} set{_AccountType= value; Notify("accounttype"); } }
我使用一个名为 ProgramModel 的类作为 Mainpage 和 FileModel 页面之间的中间点,代码如下:
public class ProgramModel : INotifyPropertyChanged
{
public ObservableCollection<FileModel> Files { get; set; }
private FileModel _currentItem;
public FileModel CurrentItem { get { return _currentItem; } set { _currentItem = value; Notify("CurrentItem"); } }
public ProgramModel()
{
Files = new ObservableCollection<FileModel>();
}
为了完成它,我有我的主页:
internal partial class MainWindow
{
public ProgramModel Model { get; set; }
private ViewSettings _viewSettings = new ViewSettings();
public MainWindow()
{
InitializeComponent();
this.DataContext = Model = new ProgramModel();
}
private void Save_Click(object sender, RoutedEventArgs e)
{
FileModel filemodel = new FileModel();
Model.Files.Add(new FileModel( filemodel.bankaccount, filemodel.accountnumber, filemodel.accounttype));
}
我觉得我从保存按钮事件中错误地添加到文件集合中。如果你们能帮助我,那就太好了!所有 3 个文本框和列表框都在主页上。如果您有任何问题,请告诉我。此外,这是一种学习体验,所以如果我发布的代码太多或不够,请告诉我。谢谢!
【问题讨论】:
-
像
bankaccount这样的属性应该是PascalCased。
标签: c# wpf xaml data-binding listbox