WPF列表框绑定问题 [英] WPF List Box Binding Issue
本文介绍了WPF列表框绑定问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
我正在尝试为WPF MVVM开发示例应用程序。 我无法绑定列表框中的数据。 请按以下方式找到代码段
I am trying to develop sample application for WPF MVVM. I am unable to bind the data in list box. Please find the code snippet as follows
XAML
<Window x:Class="Employee.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:Employee"
xmlns:ViewModel="clr-namespace:Employee.ViewModel;assembly=Employee.ViewModel"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListBox x:Name="listBox"
HorizontalAlignment="Left" Height="152" Margin="149,34,0,0" VerticalAlignment="Top" Width="281"
ItemsSource="{Binding Employees}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<!--<TextBlock Padding="5,0,5,0" Text="{Binding Id}" />-->
<TextBlock Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
XAML.cs
namespace Employee
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
dynamic viewModel = new EmployeeViewModel();
DataContext = viewModel;
}
}
}
View-Model
View-Model
namespace Employee.ViewModel
{
public class EmployeeViewModel //: INotifyPropertyChanged
{
private EmployeeRepository _Repository;
public IEnumerable<EmployeeModel> Employees; *** TRYING TO BIND EMPLOYEE INFORMATION IN LIST BUT NOT WORKING :( ***
//public event PropertyChangedEventHandler PropertyChanged;
public EmployeeViewModel()
{
_Repository = new EmployeeRepository();
GetEmployees();
}
public void GetEmployees()
{
Employees = _Repository.GetEmployees();
}
}
}
模型
EmployeeModel contains Id and Name property and trying to bind Name property in List Box.
请帮我修复此问题;为什么它没有在列表框中显示数据。
Please help me to fix this issue; why it is not displaying the data in List Box.
谢谢
Selvakumar R
Selvakumar R
推荐答案
我看到的第一件事是 员工是一个字段而不是一个属性。
The first thing I see is that Employees is a field not a property.
最好将Employees作为ObservableCollection以便更改到了山坳在UI中可以看到。
It is also better to have Employees as an ObservableCollection so that changes to the collection would be seen in the UI.
这篇关于WPF列表框绑定问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文