我在視圖(UserControl)上有一個調用代碼隱藏文件中的方法的按鈕。我想擺脫按鈕,而是調用菜單項中的方法。不知道如何做到這一點。這裏示出了該情況的一些簡單的代碼:MainView.xaml從主窗口(窗口)調用WPF視圖(UserControl)方法
<Window x:Class="Example.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:View="clr-namespace:Example.View"
Title="MainWindow" Height="600" Width="800" Background="Green">
<Grid>
<StackPanel>
<Menu>
<MenuItem Header="File" Click="MenuItem_Click">
</MenuItem>
</Menu>
<View:MainView/>
</StackPanel>
</Grid>
MainWindow.xaml.cs
using System.Windows;
namespace Example
{
public partial class MainWindow : Window
{
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("MainWindow");
// how can I invoke MainView methods like DoWork from here?
}
}
}
:
MainWindow.xaml(的MainView嵌入)
<UserControl x:Class="Example.View.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignHeight="500" d:DesignWidth="600">
<Grid Background="Yellow">
<Button HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10" Content="Show" Click="Button_Click"/>
</Grid>
</UserControl>
個MainView.xaml.cs
using System.Windows.Controls;
namespace Example.View
{
public partial class MainView : UserControl
{
public MainView()
{
InitializeComponent();
}
private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
{
DoWork();
}
public void DoWork()
{
MessageBox.Show("MainView");
}
}
}
既然你在WPF工作中有你想過關於MVVM模式? – Rekshino
使用MVVM,你會在視圖中擁有某種屬性來觸發某些行爲並從主窗口設置該屬性嗎? – Richard
我會說,DoWork屬於ViewModel,並且如果它是強制性的,必須觸發usercontrol中的某些內容,然後通過VieModel圖層。 – Rekshino