Note that there are some explanatory texts on larger screens.

plurals
  1. POSet dependency properties in XAML when the base class is generic
    text
    copied!<p>As per the title really, how can you set a dependency property in XAML when the base class is generic? When trying to do this I get a NullReferenceException, setting the property from code behind works fine. It also works when the base class is not generic. I'm using .NET4</p> <p>Here is some sample code to demonstrate:</p> <p><strong>WindowBase.cs</strong></p> <pre><code>using System.Windows; namespace GenericDependencyPropertyTest { public class WindowBase&lt;ViewModel&gt; : Window { public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register( "Header", typeof(string), typeof(WindowBase&lt;ViewModel&gt;), new PropertyMetadata("No Header Name Assigned")); public string Header { get { return (string)GetValue(HeaderProperty); } protected set { SetValue(HeaderProperty, value); } } protected virtual ViewModel Model { get; set; } } } </code></pre> <p><strong>MainWindow.xaml</strong></p> <pre><code>&lt;local:WindowBase x:Class="GenericDependencyPropertyTest.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:GenericDependencyPropertyTest" x:TypeArguments="local:IMyViewModel" Title="MainWindow" Height="350" Width="525" Header="Test"&gt; &lt;Grid&gt; &lt;/Grid&gt; &lt;/local:WindowBase&gt; </code></pre> <p><strong>MainWindow.xaml.cs</strong></p> <pre><code>namespace GenericDependencyPropertyTest { /// &lt;summary&gt; /// Interaction logic for MainWindow.xaml /// &lt;/summary&gt; public partial class MainWindow : WindowBase&lt;IMyViewModel&gt; { public MainWindow() { InitializeComponent(); } protected override IMyViewModel Model { get { return base.Model; } set { base.Model = value; } } } } </code></pre> <p><strong>IMyViewModel.cs</strong></p> <pre><code>namespace GenericDependencyPropertyTest { public interface IMyViewModel { } } </code></pre>
 

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