天天看點

WPF 學習筆記

WPF 學習筆記

一.RichTextBox控件加載文本内容:

string Text = File.ReadAllText(filename, System.Text.Encoding.Default);
rtb_TextArea.Document = new FlowDocument(new Paragraph(new Run(Text)));
           

或者:

FileStream fs;
if (File.Exists(filename))
{
      fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
      using (fs)
      {
             TextRange text = new TextRange(rtb_TextArea.Document.ContentStart, rtb_TextArea.Document.ContentEnd);
             text.Load(fs, DataFormats.Text);
       }
}
           

或者:

using (FileStream stream = File.OpenRead(filename))
{
      TextRange documentTextRange = new TextRange(rtb_TextArea.Document.ContentStart, rtb_TextArea.Document.ContentEnd);
      string dataFormat = DataFormats.Text;
      string ext = System.IO.Path.GetExtension(filename);
      if (String.Compare(ext, ".xaml", true) == 0)
      {
            dataFormat = DataFormats.Xaml;
      }
      else if (String.Compare(ext, ".rtf", true) == 0)
      {
            dataFormat = DataFormats.Rtf;
      }
      documentTextRange.Load(stream, dataFormat);
}
           

二.RichTextBox顯示文字:

rtb_TextArea.Document.Blocks.Clear();
rtb_TextArea.Document = new FlowDocument(new Paragraph(new Run("Relevant information not found..."))); 
           

三.左鍵移動窗體代碼:

//某個區域子產品
private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ButtonState == MouseButtonState.Pressed)
            {
                this.DragMove();
            }
        }
           

或者

//整個窗體
this.MouseDown += (x, y) =>
        {
            if (y.LeftButton == MouseButtonState.Pressed)
            {
                this.DragMove();
            }
        };
           

四.引用外部資源字典方法:

在App.xaml中添加:

<ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="CustomControls/Themes/Generic.xaml"></ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
           

五.最小化,最大化,關閉

─ ☐ ✕

六.WPF中定時器的使用

DispatcherTimer dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 2);//時間:時,分,秒
dispatcherTimer.Start();
           
private void dispatcherTimer_Tick(object sender,EventArgs e)
{
	//觸發函數
}
           

七.WPF 中在ViewModel層擷取ComboBox選擇的内容:

或者:

八.wpf我在第一個窗體後建立了一個窗體,要怎麼弄才能使程式運作時先顯示我建立的那個窗體?

修改baiApp.xaml中的duStartupUri=“CustomForm.xaml”,

或者在zhiApp.cs裡重dao構

protected override void OnStartup(StartupEventArgs e)
{
	base.OnStartup(e);
	var mainwin = new CustomForm();
	Application.Current.MainWindow = mainwin;
	mainwin.Show();
}
           

九.WPF TabControl中tabPage切換觸發事件:

private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
        if (e.Source is TabControl)
        {
                //do something
                
                Dispatcher.BeginInvoke(new Action(() =>
                {
               		TabControl s = (TabControl)sender;
                    //MessageBox.Show(s.SelectedIndex.ToString());
                    if (s.SelectedIndex == 0)
                    {

                    }
                    else if (s.SelectedIndex == 1)
                    {

                    }
                }));
        }
}
           

十.讀取程式集中嵌入的資源檔案:

string txt = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + ".instructions.txt";
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream s = assembly.GetManifestResourceStream(txt);
StreamReader sr = new StreamReader(s,Encoding.GetEncoding("GB2312"));
rtb_Explain.AppendText(sr.ReadToEnd());
sr.Close();
s.Close();
           

十一.在使用wpf時同時設定了WindowStyle=“None”,ResizeMode="CanResizeWithGrip"結果視窗頂部會出現一個白邊。設定ResizeMode="NoResize"沒有白邊,但是不能由使用者自定義視窗的大小。這個問題的解決辦法:

<Window x:Class="WpfApp17.MainWindow"
        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"
        xmlns:local="clr-namespace:WpfApp17"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525" WindowChrome.WindowChrome="{DynamicResource WindowChromeKey}" AllowsTransparency="True" WindowStyle="None" ResizeMode="CanResize" MinWidth="300">
    <Window.Resources>
        <WindowChrome x:Key="WindowChromeKey">
            <WindowChrome.ResizeBorderThickness>
                <Thickness>5</Thickness>
            </WindowChrome.ResizeBorderThickness>
        </WindowChrome>
    </Window.Resources>
    <Grid>
        
    </Grid>
</Window>
           

十二、菜單浮窗示例

<Grid x:Name="nav_pnl" Height="160" Width="120" Background="White" >
            <Rectangle Width="120" Height="160" Fill="White" Margin="0 0 0 0" RadiusY="2" RadiusX="2">
                <Rectangle.Effect>
                    <DropShadowEffect Color="#FFBBBBBB" Direction="0" BlurRadius="15" RenderingBias="Quality" ShadowDepth="1"></DropShadowEffect>
                </Rectangle.Effect>
            </Rectangle>
            <StackPanel>
                <Button Margin="0 10 0 10" Background="White" BorderThickness="0" Height="30" HorizontalContentAlignment="Left" Padding="30 0 0 0">主題</Button>
                <Button Margin="0 10 0 10" Background="White" BorderThickness="0" Height="30" HorizontalContentAlignment="Left" Padding="30 0 0 0">設定</Button>
                <Button Margin="0 10 0 10" Background="White" BorderThickness="0" Height="30" HorizontalContentAlignment="Left" Padding="30 0 0 0">關于</Button>
            </StackPanel>
        </Grid>
           

十三、RichtextBox添加文字

(一)使用資料綁定

<RichTextBox FontSize="12">
     <FlowDocument>
        <Paragraph>
           <Run Text="{Binding ElementName=listofmachines, Path=SelectedItem.MachineInfo.Description}"/>
        </Paragraph>
      </FlowDocument>
</RichTextBox>
           

(二)背景添加

private void RichtxtboxInput(string txt, RichTextBox richtxtbox)
 {
      Run r = new Run(txt);
      Paragraph para = new Paragraph();
      para.Inlines.Add(r);
      richtxtbox.Document.Blocks.Clear();
      richtxtbox.Document.Blocks.Add(para);
 }

定義了一個RichtxtboxInput方法,每次隻要調用這個方法就可以了。
           

十四、Ctrl + 滑鼠滾動放大縮小字型

public partial class MainWindow : Window
    {
        double scale;
        public MainWindow()
        {
            InitializeComponent();
            scale = 1;
        }
        private void Window_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
        {

            if(Keyboard.IsKeyDown(Key.LeftCtrl))
            {
                if ( e.Delta < 0)
                {
                    scale -= 0.1;
                }
                else
                {
                    scale += 0.1;
                }
                // scale += (double)e.Delta / 35000;
                ScaleTransform transfrom = new ScaleTransform();
                transfrom.ScaleX = transfrom.ScaleY = scale;
                this.view.RenderTransform = transfrom;
            }
        }
    }
           

十五、WPF窗體兩種啟動方式:

1.App.xaml配置

<Application x:Class="超級.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:超級"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/SkinDefault.xaml"/>
                <ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/Theme.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>
           

2.代碼啟動

<Application x:Class="超級.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:超級"
              Startup="App_OnStartup">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/SkinDefault.xaml"/>
                <ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/Theme.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>
           
private  void App_OnStartup(object sender, StartupEventArgs e)
        {
            //NavigationWindow window = new NavigationWindow();
            //window.Source = new Uri("MainWindow.xaml", UriKind.Relative);
            //window.Height = 800;
            //window.Width = 800;
            //window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            //window.Show();

            Application app = new Application();
            MainWindow mv = new MainWindow();
            app.Run(mv);

            Application app1 = new Application();

            app1.StartupUri = new Uri("MainWindow.xaml"); 
            app1.Run();

        }
           

十六、TabControl的SelectionChanged事件

DataGrid作為TabControl控件的TabItem的content元素。

當操作DataGrid的不同cell時,會引發了TabControl的SelectionChanged事件的問題。

正确的使用方式有2中方法:

方法一:

private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    if (e.Source is TabControl) 
    { 
      //do work when tab is changed 
    } 
}
           

此方法可判斷引發TabControl的selectionChanged的源是誰,隻有TabControl自己才會做一些處理,其他控件不做處理。

方法二:

private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
   e.Handled = true;
}
           

此方法可注冊DataGrid的SelectionChanged事件來屏蔽tabControl Changed 事件。

十七、解決在使用wpf時同時設定了WindowStyle=“None”,ResizeMode="CanResizeWithGrip"結果視窗頂部會出現一個白邊

<Window x:Class="WpfApplication1.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" WindowChrome.WindowChrome="{DynamicResource WindowChromeKey}" AllowsTransparency="True" WindowStyle="None" ResizeMode="CanResizeWithGrip">
    <Window.Resources>
        <WindowChrome x:Key="WindowChromeKey">
            <WindowChrome.ResizeBorderThickness>
                <Thickness>5</Thickness>
            </WindowChrome.ResizeBorderThickness>
        </WindowChrome>
    </Window.Resources>
    <Grid>
        <Button Content="Close" Click="ButtonBase_OnClick"></Button>
    </Grid>
</Window>
           

十八、設定文本框輸入法:

1.設定文本框隻能輸入字母:

2.初始英文輸入:

十九、關鍵幀動畫

<Window x:Class="WpfApp14.MainWindow"
        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"
        xmlns:local="clr-namespace:WpfApp14"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded">
    <Window.Triggers>
        <EventTrigger RoutedEvent="Window.Loaded">
            <BeginStoryboard>
                <Storyboard RepeatBehavior="Forever">
                    <StringAnimationUsingKeyFrames Storyboard.TargetName="text" Storyboard.TargetProperty="Text">
                        <DiscreteStringKeyFrame Value="" KeyTime="0:0:0"/>
                        <DiscreteStringKeyFrame Value="T" KeyTime="0:0:0.2"/>
                        <DiscreteStringKeyFrame Value="Te" KeyTime="0:0:0.4"/>
                        <DiscreteStringKeyFrame Value="Tes" KeyTime="0:0:0.6"/>
                        <DiscreteStringKeyFrame Value="Test" KeyTime="0:0:0.8"/>
                        <DiscreteStringKeyFrame Value="T" KeyTime="0:0:1"/>
                    </StringAnimationUsingKeyFrames>
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Window.Triggers>
    <Grid>
        <TextBlock x:Name="text" Text=""></TextBlock>
    </Grid>
</Window>
           

或者在背景處理上述事件觸發器中的内容:

private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            string animationText = "Testing ...";
            StringAnimationUsingKeyFrames keyFrames = new StringAnimationUsingKeyFrames();

            string temp = "";
            for(int i = 0;i < animationText.Length;i++)
            {
                keyFrames.KeyFrames.Add(new DiscreteStringKeyFrame { Value = temp,KeyTime = TimeSpan.FromMilliseconds(200 * (i))});
                temp += animationText[i].ToString();
            }
            keyFrames.RepeatBehavior = RepeatBehavior.Forever;
            this.text.BeginAnimation(TextBlock.TextProperty, keyFrames);
        }
           

二十、wpf window 最大化不覆寫工作列

WPF

繼續閱讀