c# - WPF:如何使 View 动态化?

标签 c# wpf xaml mvvm

我有以下xaml:需要什么才能在运行时动态填充以下xaml,但是如何? MainWorkspaceViewModel具有一个名为“ View ”的属性。此属性是对象类型,因此我可以在其中设置每个 View 。

<UserControl x:Class="DesignerWorkspace.Views.MainWorkspaceView"
             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" 
             xmlns:local="clr-namespace:DesignerWorkspace.Views"
             xmlns:vm="clr-namespace:DesignerWorkspace.ViewModels"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">        
    <Grid>
        <ContentControl Content="{Binding View}"/>
    </Grid>
</UserControl>

最佳答案

最低要求是添加一个上下文,该上下文的属性 View 和更新已更改。

然后,您可以从代码的其他位置通过设置新 View 来管理显示的 View 。

这是一个简化的实现,可能缺少要添加的检查。

class MainWorkspaceViewModel : INotifyPropertyChanged
{
    private object _view;
    public object View {
        get { return _view; }
        set { _view = value; OnPropertyChanged(); }
    }
    public event PropertyChangedEventHandler PropertyChanged = delegate { };
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

internal class MyViewManager
{
    internal static MainWorkspaceView MakeMainView()
    {
        var view = new MainWorkspaceView();
        view.DataContext = new MainWorkspaceViewModel();
        return view;
    }

    internal static void UpdateView(MainWorkspaceViewModel viewmodel, object _next)
    {
        viewmodel.View = _next;
    }
    internal static void UpdateView(MainWorkspaceView view, object _next)
    {
        (view.DataContext as MainWorkspaceViewModel).View = _next;
    }
}

关于c# - WPF:如何使 View 动态化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47672371/

相关文章:

c# - 在线设计名片应该使用pixel还是cm?

C# Web API POST 时出现错误 404

wpf - 列表框:选定的项目未突出显示

c# - .Net Matrix3D Transform() 究竟做了什么/为什么我得到 "- infinity"?

c# - 禁用 ToolbarItem Xamarin.Forms

wpf - 您如何在大型项目中组织 WPF 资源?

c# - 您在哪些方面使用 C# Lambda 表达式?

c# - 如何在 WPF 中制作具有单个捕捉点的 Slider 控件?

c# - 单击按钮后如何更改模板

c# - 如何访问调用异步方法时可用的变量?