我希望能够通过XAML中的静态资源声明DataContext,将其作为Northwind数据库中客户的绑定。我可以在代码(C#)中轻松实现此操作,但想学习如何在XAML中实现。我已经尝试了所有我能找到的例子,但都无法正常工作。我相信问题出在我标记为[Option1]和[Option2]的两行XAML代码中。您能否澄清这个语法应该是什么样子的?
namespace DataGridEF
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
bModel1 bNorthWind = new bModel1();
//this.DataContext = bNorthWind;
bNorthWind.GetCustomers();
}
}
}
namespace DataGridEF
{
public class bModel1
{
List<Customer> _Customers;
public List<Customer> Customers
{
get { return _Customers; }
set { _Customers = value; }
}
public void GetCustomers()
{
NorthwindEntities NorthWind = new NorthwindEntities();
var CustomerQ = from cust in NorthWind.Customers select cust;
_Customers = CustomerQ.ToList();
}
}
}
XAML
<Window x:Class="DataGridEF.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"
xmlns:vm="clr-namespace:DataGridEF">
<Window.Resources>
<vm:bModel1 x:Key="TheViewModel" />
</Window.Resources>
<Grid>
<DataGrid AutoGenerateColumns="False" Height="195"
HorizontalAlignment="Left" Margin="20,89,0,0"
Name="dataGrid1" ItemsSource="{Binding Path=Customers}"
[option1]DataContext="{StaticResource TheViewModel}"
[option2]DataContext=
"{Binding Path=., Source={StaticResource TheViewModel}}"
VerticalAlignment="Top" Width="471" >
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Path=ContactName}" />
<DataGridTextColumn Header="Address" Binding="{Binding Path=Address}" />
<DataGridTextColumn Header="City" Binding="{Binding Path=City}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
Window.DataContext
(<Window.DataContext><vm:bModel1 /></Window.DataContext>
),您就不需要在数据网格上设置DataContext
。 - Zev Spitz