如何使用 StaticResource 在 XAML 中定义 DataContext

发布于 2024-09-14 13:34:19 字数 2292 浏览 6 评论 0原文

我想通过 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>

I want to declare a DataContext through a static resource in XAML as a binding for the Customers in the Northwind database. I can do this easily in code (C#) but want to learn how to do in XAML. I have tried all of the examples I can find but none of them work for me. I believe the issue is in the two XAML lines of code I have labeled [Option1] and [Option2]. Can you clarify what the syntax for this really should be?

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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一指流沙 2024-09-21 13:34:19

如果为了避免使用实体框架和 MSSQL NorthWind 数据库使问题复杂化,那么代码项目“WPF/MVVM 快速入门教程"

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

此方法的另一个变体可以在 “在代码中设置 DataContext 而不是 XAML 的优点是什么?”,这部分:

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

DataContext 定义从代码隐藏迁移到 XAML 与 StaticResourceDynamicResource 的使用无关。请参阅:WPF 中的 StaticResource 和 DynamicResource 有什么区别? 可能在 codeproject WPF:StaticResource vs. DynamicResource

相关、有用和进一步阅读:

If to avoid complicating the question with Entities Framework and MSSQL NorthWind database, then the good illustration is provided in Example2 sample code of codeproject "WPF/MVVM Quick Start Tutorial"

For your XAML you should change the beginning of it to:

<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>

Another variation of this approach can be seen in "What is the advantage of setting DataContext in code instead of XAML?", the part:

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

Migrating DataContext definition from codebehind to XAML is unrelated to the usage of either StaticResource or DynamicResource. See: What's the difference between StaticResource and DynamicResource in WPF? probably better addressed in codeproject WPF: StaticResource vs. DynamicResource

Related, helpful and further reading:

郁金香雨 2024-09-21 13:34:19

我更喜欢将键设置为静态字符串 - 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 的类型。

I prefer to set the key as a static string - WPF has enough magic strings without cornering yourself into a refactoring corner if you can easily avoid it.

in 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}"/>

in App.xaml.cs

public static readonly string MainVmResourceKey = "MainVm";

in my various Control.xaml

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

note the UserControl part is whatever type you want to apply the ViewModel to.

翻了热茶 2024-09-21 13:34:19
<Window xmlns:vm="clr-namespace:YourApplication.ViewModels">

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

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

</Window>

编辑:

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

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

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

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

</Window>

Edit:

Unlike the other answers, this one attempts to simply show you exactly how to define a ViewModel as a StaticResource in XAML and use that resource for a DataContext.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文