Add a usercontrol to caliburm micro dynamically

2019-08-28 06:18发布

问题:

I am using Caliburn Micro with WPF. I want to create an application with a menu on the left side, and a grid on the right side of the application. When clicking on a menu item, the grid on the right side, will change to another view. The another view will be in a separate file.

MainWindowView:

<UserControl x:Class="CMDemo.Views.MainWindowView"
         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="300" d:DesignWidth="300">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="90*" />
        <ColumnDefinition Width="210*" />
    </Grid.ColumnDefinitions>
    <StackPanel Name="LeftMenu">
        <Button Name="ChangeDisplay" Content="Click Me"></Button>
        <TextBlock x:Name="MyString"></TextBlock>
    </StackPanel>
    <Grid Grid.Column="1" x:Name="MainGridContent" />
</Grid>

MainWindowViewModel:

public class MainWindowViewModel : PropertyChangedBase
{

    private UserControl mainGridContent;
    private string myString;

    public UserControl MainGridContent 
    {
        get { return this.mainGridContent; }
        set
        {
            this.mainGridContent = value;
            NotifyOfPropertyChange(() => this.MainGridContent);
        }   
    }

    public string MyString
    {
        get { return this.myString; }
        set
        {
            this.myString = value;
            NotifyOfPropertyChange(() => this.MyString);
        }
    }

    public void ChangeDisplay()
    {
        this.MainGridContent = new ChangeDisplayView();
        this.MyString = "Testing....";
    }

}

The changeDisplayViewModel:

public class changeDisplayViewModel: PropertyChangedBase
{
}

The changeDisplayView:

<UserControl x:Class="CMDemo.Views.changeDisplayView"
         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="300" d:DesignWidth="300">
<Grid>
    <TextBox content="Hello Caliburn Micro">
</Grid>

When I click the "Click Me" button the TextBlock "MyString" is updated and showing, but the usercontrol is not. What am I doing wrong?

回答1:

Try changing MainGridContent to a changeDisplayViewModel rather than the view itself.