我有以下代码:
MainWindow.xaml
<Window x:Class="SampleApplication.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" DataContext="{Binding Employee}"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="200" /> </Grid.ColumnDefinitions> <Label Grid.Row="0" Grid.Column="0" Content="ID:"/> <Label Grid.Row="1" Grid.Column="0" Content="Name:"/> <TextBox Grid.Column="1" Grid.Row="0" Margin="3" Text="{Binding EmpID}" /> <TextBox Grid.Column="1" Grid.Row="1" Margin="3" Text="{Binding EmpName}" /> </Grid> </Window>
Employee.cs
namespace SampleApplication { public class Employee { public Employee() { EmployeeDetails employeeDetails = new EmployeeDetails(); employeeDetails.EmpID = 123; employeeDetails.EmpName = "ABC"; } } public class EmployeeDetails { private int empID; public int EmpID { get { return empID; } set { empID = value; } } private string empName; public string EmpName { get { return empName; } set { empName = value; } } } }
这是非常简单的代码,我只想将Employee.cs类中的EmpID和EmpName属性绑定到MainWindow.xaml中Textboxes的Text属性,但是当我运行代码时,这些文本框中没有任何显示。绑定正确吗?
EmpID
EmpName
此代码将始终失败。
如所写,它说:“在我的DataContext属性上查找一个名为“ Employee”的属性,并将其设置为DataContext属性”。显然,这是不对的。
要使代码正常工作,请将窗口声明更改为:
<Window x:Class="SampleApplication.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:SampleApplication" Title="MainWindow" Height="350" Width="525"> <Window.DataContext> <local:Employee/> </Window.DataContext>
这将声明一个新的XAML名称空间(本地),并将DataContext设置为Employee类的实例。这将使您的绑定显示默认数据(来自构造函数)。
但是,这实际上不是您想要的。相反,您应该有一个新类(称为MainViewModel),该类具有一个Employee您随后绑定到的属性,如下所示:
Employee
public class MainViewModel { public Employee MyEmployee { get; set; } //In reality this should utilize INotifyPropertyChanged! }
现在,您的XAML变为:
<Window x:Class="SampleApplication.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:SampleApplication" Title="MainWindow" Height="350" Width="525"> <Window.DataContext> <local:MainViewModel/> </Window.DataContext> ... <TextBox Grid.Column="1" Grid.Row="0" Margin="3" Text="{Binding MyEmployee.EmpID}" /> <TextBox Grid.Column="1" Grid.Row="1" Margin="3" Text="{Binding MyEmployee.EmpName}" />
现在,您可以添加(其他类型,名称的)其他属性。有关更多信息,请参见实现Model-View- ViewModel模式。