我有以下 xaml:以下 xaml 必须在运行时动态填充需要什么,但是如何填充? MainWorkspaceViewModel 有一个名为“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>
最低限度是添加一个上下文,其中的视图和属性更新已更改。
然后,您可以从代码中的其他位置通过设置新视图来管理显示的视图。
这是一个简单的实现,其中缺少您可能想要添加的检查。
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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)