Search code examples
c#wpfuser-controls

WPF Window does not load UserControl


I guess I've got a pretty simple problem. I'm tying show a usercontrol via contentcontrol. What a did is to create this usercontrol...

<UserControl x:Class="Exxeta.ModeldrivenCostEstimation.WPF.UserControlModelAnalysis"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="350" d:DesignWidth="525">
<Grid Margin="0,0,0,0">
    <Grid Background="#FFE5E5E5" HorizontalAlignment="Right" Width="489" Margin="0,93,11,0" Height="164" VerticalAlignment="Top" >
        <DataGrid x:Name="DataGrid" HorizontalAlignment="Left" VerticalAlignment="Top"
            Width="489" AutoGenerateColumns="False" ItemsSource="{Binding ViewModelModelAnalysis.GridObjects}" CanUserResizeRows="False" CanUserResizeColumns="False">
        </DataGrid>
    </Grid>


</Grid>

and declared the contentControl on my mainwindow

<Window x:Class="WPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Test" Height="350" Width="525" ResizeMode="NoResize" Background="#FFE5E5E5">
    <ContentControl Name="Content"  Width="Auto" Opacity="1" Background="Transparent" ></ContentControl>
</Window>

.. And as I read I create the windows like this.

public MainWindow(***)
{
    InitializeComponent();
    model = new BasicViewModel();
    UserControl c1 = new UserControlModelAnalysis();
    this.Content = c1;
    this.DataContext = model;

}

But the content is not shown by the window. Did I missed something there ? Hope you can help me out of this little issue.

Thanks for your help Iki


Solution

  • Edit: Whats happening is that the MainWindow.Content PUBLIC field is hiding the base classes Content property. You are setting the content field to your UserControl which is also a ContentControl hence no type cast error. Because The MainWindow.Content field is not a dependency property the UI is never updated and your content is not shown.

    Answer: Rename your ContentControl and set the content property on the control.

    This works.

    Xaml

    <Window x:Class="Example_Project.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">
        <Grid>
            <ContentControl x:Name="currentContent"/>
        </Grid>
    </Window>
    

    Code Behind

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
    
            currentContent.Content = new Content1();
        }
    }