gpt4 book ai didi

c# - 如何在中间是其他窗口的占位符的 WPF 中创建布局?

转载 作者:行者123 更新时间:2023-11-30 23:05:28 25 4
gpt4 key购买 nike

我正在尝试使用 WPF 创建一个应用程序。我想在顶部和右侧创建一个带有大按钮的主窗口。单击按钮时,我想像这样在中间渲染相应的窗口。 enter image description here

我不确定如何制作这种外观以及如何将布局分配为其中打开其他窗口的父布局。

这是我失败的 XAML 尝试

```

    <Menu DockPanel.Dock="Top" Height="50" VerticalAlignment="Center">
<MenuItem Header="File" Height="50" VerticalAlignment="Center"></MenuItem>
<MenuItem Header="View"></MenuItem>
</Menu>

<Menu DockPanel.Dock="Right" Width="50"></Menu>


</DockPanel>

```

是否可以在 WPF 中为其他窗口实现带占位符的布局?我怎么能做这样的事情?

最佳答案

我建议为您的子窗口使用 UserControlsDataTemplate 绑定(bind)将是对此的理想设置。

内容控件将绑定(bind)到 CurrentView 属性。CurrentView 内容由关联的 DataTemplate 解析。这将根据 CurrentView 引用的数据类型实例在占位符中呈现所选 View 。

MainWindow.xaml.cs

public MainWindow()
{
this.DataContext = new MainWindowViewModel();
}

ViewModel.cs

public class ViewModel : INotifyPropertyChanged
{
... Implement INotifyPropertyChanged
}

FirstViewModel.cs

public class FirstViewModel : ViewModel 
{
...
}

SecondViewModel.cs

public class SecondViewModel : ViewModel 
{
...
}

MainWindowViewModel.cs

public class MainWindowViewModel : ViewModel
{
public ICommand Button1Command { get; }
public ICommand Button2Command { get; }

private ViewModel _currentView { get; }

protected ViewModel FirstView { get; }
protected ViewModel SecondView { get; }

public ViewModel CurrentView
{
get { return _currentView; }
set { _currentView = value; NotifyPropertyChanged(); }
}

public MainWindowViewModel()
{
this.FirstView = new FirstViewModel();
this.SecondView= new SecondViewModel();
this.Button1Command = new RelayCommand(OnButton1);
this.Button2Command = new RelayCommand(OnButton2);
}

public void OnButton1()
{
this.CurrentView = this.FirstView;
}

public void OnButton2()
{
this.CurrentView = this.SecondView;
}
}

主窗口.xaml

<Window.Resources>
<ResourceDictionary>
<DataTemplate DataType="{x:Type vm:FirstViewModel}">
<Label>Menu View</Label>
<!-- Or you could embed a User Control -->
<views:MenuView />
</DataTemplate>

<DataTemplate DataType="{x:Type vm:SecondViewModel}">
<Label>Other View</Label>
<!-- Or you could embed a User Control -->
<views:OtherView />
</DataTemplate>
</ResourceDictionary>
</Window.Resources>

<DockPanel LastChildFill="True">

<StackPanel DockPanel.Dock="Top">
<Button Command="{Binding Button1Command}">Menu Button</Button>
<Button Command="{Binding Button2Command}">Other Button</Button>
</StackPanel>

<ContentControl Content="{Binding CurrentView}"></ContentControl>
</DockPanel>

关于c# - 如何在中间是其他窗口的占位符的 WPF 中创建布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48811765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com