精通C#---WPF和XAML

1.WPF之前功能和解决方法
控件表单 Windows Forms
2D 图形API
3D DirectX API
流视频 Windows Media Player API
流文档 PDF

简单UI元素
交互的二维,三维图像
动画
多媒体

2.Application

Current
MainWindow
Properties
StartupUri
Windows

//
class MyApp : Application
{
	[STAThread]
	static void Main()
	{
		MyApp app = new MyApp();
		app.Startup += (s, e)=>{};
		app.Exit += (s, e)=>{};
	}
}

//
static void MinimizeAllWindows()
{
	foreach(Window wnd in Application.Current.Windows)
	{
		wnd.WindowState = WindowState.Minimized;
	}
}

3.System.Windows.Controls.Control
Background, Foreground, BorderBrush, BorderThickness, Padding, HorizontalContentAlignment, VerticalContentAlignment

FontFamily, FontSize, FontStretch, FontWeight
IsTabStop, TabIndex
MouseDoubleClick, PreviewMouseDoubleClick
Template

4.System.Windows.FrameworkElement
ActualHeight, ActualWidth, MaxHeight, MaxWidth, MinHeight, MinWidth, Height, Width
ContextMenu
Cursor
HorizontalAlignment, VerticalAlignment
Name
Resources
ToolTip

5.System.Windows.UIElement
Focusable, IsFocused
IsEnabled
IsMouseDirectlyOver和IsMouseOver
IsVisible, Visibility
RederTransform

6.XAML属性语法

<Button Height = "43">
</Button>

等价与
<Button>
<Button.Height>
43
</Button.Height>
</Button>

7.窗口或任何ContentControl的子类的Content属性只能设置一个对象。
如果窗口需要包含多个元素,那么这些元素须被安排在多个面板中。
面板可以容纳所有表示窗口的UI元素,而面板本身将作为唯一的对象,赋给窗口的Content属性。

// XAML
<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        WindowStartupLocation="CenterScreen">

    <Window.CommandBindings>
        <CommandBinding Command="ApplicationCommands.Open" Executed="OpenCmdExecuted" CanExecute="OpenCmdCanExecute"/>
        <CommandBinding Command="ApplicationCommands.Save" Executed="SaveCmdExecuted" CanExecute="SaveCmdCanExecute"/>
    </Window.CommandBindings>

    <DockPanel>
        <Menu DockPanel.Dock="Top" 
              HorizontalAlignment="Left" Background="White" BorderBrush="Black">
            <MenuItem Header="_File">
                <MenuItem Command="ApplicationCommands.Open"/>
                <MenuItem Command="ApplicationCommands.Save"/>
                <Separator/>
                <MenuItem Header="_Exit" MouseEnter="MouseEnterExitArea" MouseLeave="MouseLeaveArea" Click="FileExit_Click"/>
            </MenuItem>

            <MenuItem Header="_Edit">
                <MenuItem Command="ApplicationCommands.Copy"/>
                <MenuItem Command="ApplicationCommands.Cut"/>
                <MenuItem Command="ApplicationCommands.Paste"/>
            </MenuItem>

            <MenuItem Header="_Tools">
                <MenuItem Header="_Spelling Hints"
                    MouseEnter="MouseEnterToolsHintArea"
                    MouseLeave="MouseLeaveArea"
                    Click="ToolsSpellingHints_Click"/>
            </MenuItem>
        </Menu>
        
        <ToolBar DockPanel.Dock="Top">
            <Button Content="Exit" MouseEnter="MouseEnterExitArea"
                    MouseLeave="MouseLeaveArea" Click="FileExit_Click"/>
            <Separator/>
            <Button Content="Check" MouseEnter="MouseEnterToolsHintsArea"
                    MouseLeave="MouseLeaveArea" Click="ToolsSpellingHints_Click"
                    Cursor="Help"/>
        </ToolBar>

        <StatusBar DockPanel.Dock="Bottom" Background="Beige">
            <StatusBarItem>
                <TextBlock Name="statBarText" Text="Ready"/>
            </StatusBarItem>
        </StatusBar>


        <Grid DockPanel.Dock="Left" Background="AliceBlue">
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>

            <GridSplitter Grid.Column="0" Width="5" Background="Gray"/>
            <StackPanel Grid.Column="0" VerticalAlignment="Stretch">
                <Label Name="lblSpellingInstructions" FontSize="14" Margin="10, 10, 0, 0">
                    Spelling Hints
                </Label>

                <Expander Name="expanderSpelling" Header="Try these!"
                          Margin="10, 10, 10, 10">
                    <Label Name="lblSpellingHints" FontSize="12"/>
                </Expander>
            </StackPanel>

            <TextBox Grid.Column="1"
                     SpellCheck.IsEnabled="True"
                     AcceptsReturn="True"
                     Name="txtData"
                     FontSize="14"
                     BorderBrush="Blue"
                     VerticalScrollBarVisibility="Auto"
                     HorizontalScrollBarVisibility="Auto">
            </TextBox>
        </Grid>
    </DockPanel>
</Window>

// 代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 System.IO;
using System.Windows.Markup;
using System.Windows.Forms;

namespace WpfApplication2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            SetF1CommandBinding();
        }

        private void SetF1CommandBinding()
        {
            CommandBinding helpBinding = new CommandBinding(ApplicationCommands.Help);
            helpBinding.CanExecute += CanHelpExecute;
            helpBinding.Executed += HelpExecuted;
            CommandBindings.Add(helpBinding);
        }

        private void CanHelpExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void HelpExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            System.Windows.Forms.MessageBox.Show("Look, it is not that difficult. Just type something!", "Help!");
        }

        private void Window_Closed(object sender, EventArgs e)
        {}

        //private void MouseEnterExitArea(object sender, RoutedEventArgs e)
        //{}

        // private void MouseLeaveArea(object sender, RoutedEventArgs e)
        //{}

        // private void MouseEnterToolsHintArea(object sender, RoutedEventArgs e)
        //{}

        private void ToolsSpellingHints_Click(object sender, RoutedEventArgs e)
        {
            string spellingHints = string.Empty;
            SpellingError error = txtData.GetSpellingError(txtData.CaretIndex);
            if (error != null)
            {
                foreach (string s in error.Suggestions)
                {
                    spellingHints += string.Format("{0}\n", s);
                }

                lblSpellingHints.Content = spellingHints;
                expanderSpelling.IsExpanded = true;
            }
        }

        private void FileExit_Click(object sender, RoutedEventArgs e)
        {
            this.Close(); 
        }

        private void MouseEnterToolsHintsArea(object sender, RoutedEventArgs e)
        {
        }

        protected void MouseEnterExitArea(object sender, RoutedEventArgs args)
        {
            statBarText.Text = "Exit the Application";
        }

        protected void MouseEnterToolsHintArea(object sender, RoutedEventArgs args)
        {
            statBarText.Text = "Show Spelling Suggestions";
        }

        protected void MouseLeaveArea(object sender, RoutedEventArgs args)
        {
            statBarText.Text = "Ready";
        }

        private void OpenCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void SaveCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void OpenCmdExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            OpenFileDialog openDlg = new OpenFileDialog();
            openDlg.Filter = "Text Files | *.txt";
            DialogResult _nRet = openDlg.ShowDialog();
            if (_nRet == System.Windows.Forms.DialogResult.OK)
            {
                string dataFromFile = File.ReadAllText(openDlg.FileName);
                txtData.Text = dataFromFile;
            }
        }

        private void SaveCmdExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            SaveFileDialog saveDlg = new SaveFileDialog();
            saveDlg.Filter = "Text Files | *.txt";
            DialogResult _nRet = saveDlg.ShowDialog();
            if (_nRet == System.Windows.Forms.DialogResult.OK)
            {
                File.WriteAllText(saveDlg.FileName, txtData.Text);
            }
        }
     
    }
}

9.Document API
System.Windows.Documents
List
Paragraph
Section
Table
LineBreak
Figure
Floater
Span

块元素:
System.Windows.Documents.Block
内联元素:
System.Windows.Document.Inline
文档布局管理器:
FlowDocument
FixDocument

FlowDocumentReader
FlowDocumentScrollViewer
RichTextBox
FlowDocumentPageViewer

Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:a ="clr-namespace:System.Windows.Annotations;assembly=PresentationFramework"
        Title="MainWindow" Height="350" Width="525"
        WindowStartupLocation="CenterScreen">
    <StackPanel Margin="110,75,7,4.5">
        <TabControl x:Name="myTabSystem" HorizontalAlignment="Left" Height="280"
			Margin="10,0,-96,0" VerticalAlignment="Top" Width="489">
            <TabItem Header="Ink API">
                <StackPanel Margin="0,0,98,36" Orientation="Vertical">
                    <InkCanvas x:Name="myInkCanvas" Height="210"/>
                </StackPanel>
            </TabItem>
            <TabItem x:Name="tabDocuments" Header="Documents" VerticalAlignment="Bottom" Height="20">
                <StackPanel>
                    <ToolBar>
                        <Button BorderBrush="Green" Command="a:AnnotationService.CreateTextStickyNoteCommand" Content="Add Sticky Note"/>
                        <Button BorderBrush="Green" Command="a:AnnotationService.DeleteStickyNotesCommand" Content="Delete Sticky Notes"/>
                        <Button BorderBrush="Green" Command="a:AnnotationService.CreateHighlightCommand" Content="Highlight Text"/>
                        <Button x:Name="btnSaveDoc" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="75" Content="Save Doc"/>
                        <Button x:Name="btnLoadDoc" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="75" Content="Load Doc"/>
                    </ToolBar>
                    <FlowDocumentReader x:Name="myDocumentReader" Height="269.4">
                        <FlowDocument>
                            <Section Foreground="Yellow" Background="Black">
                                <Paragraph FontSize="20">
                                    Here are some fun facts about the WPF Documents API!
                                </Paragraph>
                            </Section>
                            <List x:Name="listOfFunFacts"/>
                            <Paragraph x:Name="paraBodyText"/>
                        </FlowDocument>
                    </FlowDocumentReader>
                </StackPanel>
            </TabItem>
            <TabItem x:Name="tabDataBinding" Header="Data Binding">
                <StackPanel Width="250" DataContext="{Binding ElementName=mySB}">
                    <Label Content="Move the scroll bar to see the current value"/>
                    <ScrollBar x:Name="mySB" Orientation="Horizontal" Height="30" Minimum="1" Maximum="100" LargeChange="1" SmallChange="1"/>
                    <Label x:Name="labelSBThumb" Height="30" BorderBrush="Blue" BorderThickness="2"/>
                    <Button Content="Click" FontSize="{Binding Path=Value}" Height="140"/>
                </StackPanel> 
            </TabItem>
            <TabItem x:Name="tabDataGrid" Header="DataGrid">
                <StackPanel>
                    <DataGrid x:Name="gridInventory" Height="288"/>
                </StackPanel>
            </TabItem>
        </TabControl>
        <ToolBar x:Name="inkToolBar" Height="60">
            <Border Margin="0,2,0,3" Width="300">
                <Grid>
                    <RadioButton Click="RadioButtonClicked" x:Name="inkRadio" Content="Ink Mode!" GroupName="InkMode" Margin="0,0,200,0"/>
                    <RadioButton Click="RadioButtonClicked" Content="Erase Mode!" GroupName="InkMode" Margin="100,0"/>
                    <RadioButton Click="RadioButtonClicked" Content="Select Mode!" GroupName="InkMode" Margin="200,0,0,0"/>
                </Grid>
            </Border>
            <Separator/>
            <ComboBox x:Name="comboColors" Width="100">
                <ComboBoxItem Content="Red"/>
                <ComboBoxItem Content="Green"/>
                <ComboBoxItem Content="Blue"/>
            </ComboBox>
        </ToolBar>
        <Button x:Name="btnSave" Click="SaveData" Content="Button"/>
        <Button x:Name="btnLoad" Click="LoadData" Content="Button"/>
        <Button x:Name="btnClear" Click="Clear" Content="Button"/>

    </StackPanel>


</Window>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 System.IO;
using System.Windows.Markup;
using System.Windows.Forms;
using System.Windows.Controls;
using System.Windows.Ink;
using System.Windows.Annotations;
using System.Windows.Annotations.Storage;

namespace WpfApplication2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            this.InitializeComponent();

            this.myInkCanvas.EditingMode = InkCanvasEditingMode.Ink;
            this.inkRadio.IsChecked = true;
            this.comboColors.SelectedIndex = 0;
            PopolateDocument();
            EnableAnnotations();

            btnSaveDoc.Click += (o, s) =>
                {
                    using(FileStream fStream = File.Open("documentData.xaml", FileMode.Create))
                    {
                        XamlWriter.Save(this.myDocumentReader.Document, fStream);
                    }
                };

            btnLoadDoc.Click += (o, s) =>
                {
                    using (FileStream fStream = File.Open("documentData.xaml", FileMode.Open))
                    {
                        try
                        {
                            FlowDocument doc = XamlReader.Load(fStream) as FlowDocument;
                            this.myDocumentReader.Document = doc;
                        }
                        catch (Exception ex)
                        {
                            System.Windows.Forms.MessageBox.Show(ex.Message, "Error Loading Doc!");
                        }
                    }
                };

            SetBindings();
        }

        private void SetBindings()
        {
            System.Windows.Data.Binding b = new System.Windows.Data.Binding();
            b.Converter = new MyDoubleConverter();
            b.Source = this.mySB;
            b.Path = new PropertyPath("Value");
            this.labelSBThumb.SetBinding(System.Windows.Controls.Label.ContentProperty, b);
        }

        private void EnableAnnotations()
        {
            AnnotationService anoService = new AnnotationService(myDocumentReader);
            MemoryStream anoStream = new MemoryStream();
            AnnotationStore store = new XmlStreamStore(anoStream);
            anoService.Enable(store);
        }

        private void RadioButtonClicked(object sender, System.Windows.RoutedEventArgs e)
        { 
            switch((sender as System.Windows.Controls.RadioButton).Content.ToString())
            { 
                case "Ink Mode!":
                    {
                        this.myInkCanvas.EditingMode = InkCanvasEditingMode.Ink;
                    }
                    break;
                case "Erase Mode!":
                    {
                        this.myInkCanvas.EditingMode = InkCanvasEditingMode.EraseByStroke;
                    }
                    break;
                case "Select Mode!":
                    {
                        this.myInkCanvas.EditingMode = InkCanvasEditingMode.Select;
                    }
                    break;
            }
        }

        private void ColorChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            string colorToUse = (this.comboColors.SelectedItem as StackPanel).Tag.ToString();
        }

        private void SaveData(object sender, System.Windows.RoutedEventArgs e)
        {
            using(FileStream fs = new FileStream("StrokeData.bin", FileMode.Create))
            {
                this.myInkCanvas.Strokes.Save(fs);
                fs.Close();
            }
        }

        private void LoadData(object sender, System.Windows.RoutedEventArgs e)
        {
            using(FileStream fs = new FileStream("StrokeData.bin", FileMode.Open, FileAccess.Read))
            {
                StrokeCollection strokes = new StrokeCollection(fs);
                this.myInkCanvas.Strokes = strokes;
            }
        }

        private void Clear(object sender, System.Windows.RoutedEventArgs e)
        {
            this.myInkCanvas.Strokes.Clear();
        }

        private void PopolateDocument()
        {
            this.listOfFunFacts.FontSize = 14;
            this.listOfFunFacts.MarkerStyle = TextMarkerStyle.Circle;
            this.listOfFunFacts.ListItems.Add(new ListItem(new Paragraph(new Run("Fixed documents are for WYSIWYG print ready docs!"))));
            this.listOfFunFacts.ListItems.Add(new ListItem(new Paragraph(new Run("The API supports tables and embedded figures!"))));
            this.listOfFunFacts.ListItems.Add(new ListItem(new Paragraph(new Run("Flow documents are read only!"))));
            this.listOfFunFacts.ListItems.Add(new ListItem(new Paragraph(new Run("BlockUIContainer allows you to embed WPF controls in the document!"))));

            Run prefix = new Run("This paragraph was generated");
            Bold b = new Bold();
            Run infix = new Run("dynamically");
            infix.Foreground = Brushes.Red;
            infix.FontSize = 30;
            b.Inlines.Add(infix);

            Run suffix = new Run("at runtime!");
            this.paraBodyText.Inlines.Add(prefix);
            this.paraBodyText.Inlines.Add(infix);
            this.paraBodyText.Inlines.Add(suffix);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace WpfApplication2
{
    class MyDoubleConverter : IValueConverter
    {
        // 源--> 目标
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            double v = (double)value;
            return (int)v;
        }

        // 目标-->源
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value;
        }
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

raindayinrain

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值