Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to define DataContext in XAML using StaticResource
    primarykey
    data
    text
    <p>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?</p> <p><strong>C#</strong></p> <pre><code>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&lt;Customer&gt; _Customers; public List&lt;Customer&gt; 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(); } } } </code></pre> <p><strong>XAML</strong></p> <pre><code> &lt;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"&gt; &lt;Window.Resources&gt; &lt;vm:bModel1 x:Key="TheViewModel" /&gt; &lt;/Window.Resources&gt; &lt;Grid&gt; &lt;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" &gt; &lt;DataGrid.Columns&gt; &lt;DataGridTextColumn Header="Name" Binding="{Binding Path=ContactName}" /&gt; &lt;DataGridTextColumn Header="Address" Binding="{Binding Path=Address}" /&gt; &lt;DataGridTextColumn Header="City" Binding="{Binding Path=City}" /&gt; &lt;/DataGrid.Columns&gt; &lt;/DataGrid&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload