Jim*_*mas 7 c# wpf datacontext xaml
我想通过XAML中的静态资源声明一个DataContext,作为Northwind数据库中Customers的绑定.我可以在代码(C#)中轻松完成此操作,但想学习如何在XAML中完成.我已经尝试了所有可以找到的例子,但它们都不适合我.我认为这个问题出现在我标记为[Option1]和[Option2]的两行XAML代码行中.你能澄清一下这个语法应该是什么吗?
C#
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
如果为了避免使实体框架和MSSQL NorthWind数据库的问题复杂化,那么在Exampleproject" WPF/MVVM快速入门教程 "的 示例2示例代码中提供了很好的说明.
对于您的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.DataContext>
<vm:bNorthWind />
</Window.DataContext>
<Grid>
<!---Couldnt check your code due to dependencies on
EF and MSSQL NorthWind database
See the reference for working illustration sample:
http://www.codeproject.com/Articles/165368/WPF-MVVM-Quick-Start-Tutorial
-->
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)
这种方法的另一种变体可以在"在代码中设置DataContext而不是XAML的优势是什么?"中可以看到., 那个部分:
<StackPanel.DataContext>
<local:CustomerViewModel />
</StackPanel.DataContext>
Run Code Online (Sandbox Code Playgroud)
迁移DataContext从代码隐藏到XAML定义是无关的任一使用StaticResource或DynamicResource.请参阅: WPF中StaticResource和DynamicResource之间的区别是什么?可能在codeproject WPF中更好地解决:StaticResource与DynamicResource
相关,有用和进一步阅读:
| 归档时间: |
|
| 查看次数: |
18263 次 |
| 最近记录: |