Design a notepad application in WPF.
MainWindow.xaml
<Window x:Class="Notepad.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Notepad" Height="350" Width="525">
<Grid>
<TextBox Height="262" HorizontalAlignment="Left" Margin="12,29,0,0" Name="txtText" VerticalAlignment="Top" Width="479" />
<Menu Height="23" HorizontalAlignment="Left" Name="menu1" VerticalAlignment="Top" Width="491" >
<MenuItem Header="_File" >
<MenuItem Header="_New" Click="mnuNew_Click" />
<MenuItem Header="_Open" Click="mnuOpen_Click" />
<MenuItem Header="_Save" Click="mnuSave_Click"/>
<Separator />
<MenuItem Header="_Exit" Click="mnuExit_Click"/>
</MenuItem>
</Menu>
</Grid>
</Window>
App.xaml
<Application x:Class="Notepad.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>
MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.IO;
namespace Notepad
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private string fileName;
private const string FILE_FILTER = "Text|*.txt|All|*.*";
public MainWindow()
{
InitializeComponent();
}
/// <summary>
///New menu item
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void mnuNew_Click(object sender, RoutedEventArgs e)
{
txtText.Text = "";
fileName = "";
}
/// <summary>
/// Open menu item
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void mnuOpen_Click(object sender, RoutedEventArgs e)
{
// Create OpenFileDialog
OpenFileDialog openFileDlg = new OpenFileDialog();
openFileDlg.Filter =FILE_FILTER;
if (openFileDlg.ShowDialog() == true)
{
fileName = openFileDlg.FileName;
txtText.Text = System.IO.File.ReadAllText(openFileDlg.FileName);
}
}
/// <summary>
/// Save menu item
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void mnuSave_Click(object sender, RoutedEventArgs e)
{
if (fileName == "")
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = FILE_FILTER;
if (saveFileDialog.ShowDialog() == true)
{
fileName = saveFileDialog.FileName;
}
}
File.WriteAllText(fileName, txtText.Text);
}
/// <summary>
/// Exit menu item
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void mnuExit_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
}
Example
Comments
Leave a comment