将用户控件动态添加到caliburm micro

时间:2012-06-10 18:29:32

标签: c# wpf user-controls caliburn.micro

我正在使用Caliburn Micro和WPF。我想在左侧创建一个带有菜单的应用程序,并在应用程序的右侧创建一个网格。单击菜单项时,右侧的网格将更改为另一个视图。另一个视图将在一个单独的文件中。

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....";
    }

}

changeDisplayViewModel:

public class changeDisplayViewModel: PropertyChangedBase
{
}

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>

当我单击“单击我”按钮时,TextBlock“MyString”会更新并显示,但用户控件不会。我做错了什么?

1 个答案:

答案 0 :(得分:1)

尝试将MainGridContent更改为changeDisplayViewModel而不是视图本身。