0

So, I have made my own subclass of UserControl, called ChildView (I really can't come up with a decent name), that I want to show inside a container in a window, I have many different kinds of these UserControls and the window must be capable of showing all of them. The UserControls have implemented my subclass like this:

<src:ChildView x:Class="(namespace).LoginView" [...]>
public partial class LoginView : ChildView

And I have tried to add it to my window like so:

<Grid x:Name="ViewHolder" Grid.Column="1" Grid.Row="1">
        <src:ChildView DataContext="{Binding CurrentView}" />
</Grid>
private ChildView _currentView;
public ChildView CurrentView 
{
    get { return _currentView; }
    set
    {
        if (_currentView == value)
            return;

        _currentView = value;
        smLog.Trace("View set to {0}", value.GetType().Name);
        NotifyPropertyChanged("CurrentView");
    }
}

However, this does not work. Nothing is shown in my container when I set CurrentView. There are no error messages in the output that would indicate a problem with the binding. Other data bindings in the window works. I can use my ChildViews by specifying their classes directly in the XAML, i.e:

<Grid x:Name="ViewHolder" Grid.Column="1" Grid.Row="1">
        <src:LoginView />
</Grid>

I've read some about dependency properties but I don't think I need one here? I did try to implement one anyway but it didn't seem to help, though I probably made some mistake, I couldn't quite wrap my head around it...

So I guess my question is; do I need a dependency property? If so, how do I implement it in this case? If not, what is the problem?

moggizx
  • 476
  • 1
  • 5
  • 19
  • try `snoop`. it's wpf utility and very useful to check is your control exists in grid and what exactly problems you have here – Eugene Aug 20 '13 at 09:23
  • According to Snoop my ViewHolder contains "[007] ChildView 2", and if I check its properties the DataContext is highlighted in green and says "[(namespace).LoginView] {Path=CurrentView}". IsInitialized, IsLoaded, IsVisible, IsEnabled are all true... Height and Width have reasonable values. – moggizx Aug 20 '13 at 09:35

1 Answers1

1

Changing the Child's DataContext won't matter, you're trying to change the control itself, not the data it's bound to. What you need to do is add a placeholder control that would contain the actual view. WPF has such a thing built in, take a look at ContentControl.

Change your grid so it'll containt a ContentControl instead of ChildView, and bind the view to the control's Content property

<Grid>
  <ContentControl Content="{Binding CurrentView}"/>
</Grid>
CKII
  • 1,439
  • 14
  • 26