如何使用StaticResource在XAML中定义DataContext

时间:2010-08-16 19:26:00

标签: c# wpf xaml datacontext

我想通过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();
        }

    }
}

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>

3 个答案:

答案 0 :(得分:8)

如果为了避免使问题与Entities Framework和MSSQL NorthWind数据库复杂化,那么示例2中的代码项目“WPF/MVVM Quick Start Tutorial”的示例代码中提供了很好的说明。

对于您的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>

这种方法的另一种变体可以在"What is the advantage of setting DataContext in code instead of XAML?"中看到,部分:

    <StackPanel.DataContext>
        <local:CustomerViewModel />
    </StackPanel.DataContext>   

DataContext定义从代码隐藏迁移到XAML与使用StaticResourceDynamicResource无关。请参阅:What's the difference between StaticResource and DynamicResource in WPF?可能在codeproject WPF: StaticResource vs. DynamicResource

中更好地解决

相关,有帮助和进一步阅读:

答案 1 :(得分:1)

我更喜欢将密钥设置为静态字符串 - 如果您可以轻松避开,WPF有足够的魔术字符串而不会将自己转移到重构角落。

App.xaml

中的

xmlns:viewModels="clr-namespace:MyAppNamespace.ViewModels"
xmlns:local="clr-namespace:tvCADdesktop"
x:Name="App"
...
<viewModels:ApplicationViewModel x:Key= "{x:Static local:App.MainVmResourceKey}"/>
App.xaml.cs

中的

public static readonly string MainVmResourceKey = "MainVm";

在我的各种Control.xaml

<UserControl.DataContext>
    <Binding>
        <Binding.Source>
            <StaticResource ResourceKey="{x:Static app:App.MainVmResourceKey}" />
        </Binding.Source>
    </Binding>
</UserControl.DataContext>

请注意UserControl部分是您要将ViewModel应用到的任何类型。

答案 2 :(得分:-1)

<Window xmlns:vm="clr-namespace:YourApplication.ViewModels">

    <Window.Resources>
        <vm:MainWindowViewModel x:Key="MWVM" />
    </Window.Resources>

    <Window.DataContext>
        <StaticResource ResourceKey="MWVM" />
    </Window.DataContext>

</Window>

编辑:

与其他答案不同,本篇文章试图简单地向您展示如何将ViewModel定义为XAML中的StaticResource并将该资源用于DataContext。