在ViewModel中使用WPF UserControl而不是Window

时间:2015-06-23 14:08:04

标签: wpf user-controls window

如何将MenuManagement的xaml从Window更改为UserControl?

我想在MainWindow xaml中使用MenuManagement:

        this.mainViewModel = new MainWindow();
        this.mainViewModel.Show();
        this.mainViewModel.LayoutMain.Navigate(new MenuManagement());

但我收到错误: "其他信息:' ***。Views.MenuManagement' root元素对导航无效。"

我的MenuViewModel:

    class MenuViewModel : ViewModelBase<IMainView>
{
    public MenuViewModel()
        :base(new MenuManagement())
    { //...
}}

MenuManagment的xaml

<Window x:Class="***.Views.MenuManagement"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation" 
    Title="MenuManagement" Height="720" Width="1280">
<Grid>
   ...
</Grid>

MenuManagement

    public partial class MenuManagement : Window, IMainView
{
    public MenuManagement()
    {
        InitializeComponent();
    } }

编辑: 接口

    public interface IView
{
    object DataContext { get; set; }
    void Close();
}

    public interface IMainView : IView
{
    void Show();
}

}

1 个答案:

答案 0 :(得分:0)

改变这个:

<Window x:Class="***.Views.MenuManagement"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation" 
    Title="MenuManagement" Height="720" Width="1280">
<Grid>
   ...
</Grid>

为:

<UserControl x:Class="***.Views.MenuManagement"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation" 
    Title="MenuManagement" Height="720" Width="1280">
    <Grid>
       ...
    </Grid>
</UserControl>

和此:

public partial class MenuManagement : Window, IMainView
{
    public MenuManagement()
    {
        InitializeComponent();
    } 
}

为:

public partial class MenuManagement : UserControl, IMainView
{
    public MenuManagement()
    {
        InitializeComponent();
    } 
}