locked
MVVM in UserControl RRS feed

  • Question

  • Hi all

    I'm confused about using MVVM pattern for a user control...

    Let's assume:

    MyView derives from UserControl.

    MyViewModel derives from DependencyObject and defines a couple of DPs which MyView is binding on.

    <DataTemplate DataType="{x:Type mv:MyViewModel }">
      <vw:MyView />
    </DataTemplate>
    

    So far so good...

    I'm not sure whether this is a good approach for a UserControl... Nonetheless, I tried it out in XAML:

    <mv:MyViewModel MyDP="{Binding OtherProperty}" />
    

    Because MyViewModel is no a UIElement this doesn't work...

    Therefore I tried:

    <ContentControl>
      <mv:MyViewModel MyDP="{Binding OtherProperty}" />
    </ContentControl>
    

    In this case, the binding doesn't work, because MyViewModel doesn't inherit the DataContext from the containing element (is this because MyViewModel is not in the Visual/LogicalTree??)

    I get the error: "... Cannot find governing FrameworkElement or FrameworkContentElement for target element. ..."

    It seems like MyViewModel would have to inherit from FrameworkElement... But in my opinion this would contradict the sense behind MV. Do I have to take the hack way for an "inheritance context"?

    What would you suggest? Shall I wrap my "control" in another control??

    At the end I would like to place something like

     

    <controls:MyControl MyDP="{Binding OtherProperty}" />
    
    Please clarify this for me. Any help is appreciated.

     

     

    Thursday, August 12, 2010 3:15 PM

Answers

  • consider looking at mefedMVVM by marlon grech http://mefdmvvm.codeplex.com , it might help you understand your current direction of linking view to viewmodel regardless if its a window or a usercontrol, specifically at the dependency property for viewmodel locator. 
    • Marked as answer by Dunken Friday, August 13, 2010 6:16 AM
    Friday, August 13, 2010 12:12 AM