troubleshooting Question

WPF: How to override the constructor when binding a UserControls properties

Avatar of eb8931
eb8931 asked on
Microsoft Development
1 Comment1 Solution786 ViewsLast Modified:
I have what seems to be a simple problem but I can't solve it.

I have a UserControl with the following DependencyProperty and Constructor
    public CardModel Card {
      get { return (CardModel)GetValue(CardProperty); }
      set { SetValue(CardProperty, value); }
    public static readonly DependencyProperty CardProperty =
        DependencyProperty.Register("Card", typeof(CardModel), typeof(CardView), null);

    public CardView() {
      if (Card == null) 
        Card = new CardModel();

This card is used as the ItemTemplate is a listbox as follows
  <DataTemplate x:Key="CardDataTemplate">
      <local:CardView d:LayoutOverrides="Width, Height" Card="{Binding}" />

The problem is that Card is always null when the constructor is called, irrespective of whether it is bound or not, but once Card = new CardModel() is called the binding no longer works.  

However if I take this code out of the constructor then the UserControl will not work in other situations (since the CardModel will not be set).  A third option is to set the Card to a new CardModel when registering the DepencyProperty, but this will mean that all the CardViews will point to a single instance of the CardModel.

So all I want to do is have a default constructor that sets the CardModel under normal circumstances, but still allow it to be Bound to other values.
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 1 Comment.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 1 Comment.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros