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选择的内容:
<ComboBox SelectedItem="{Binding xxx}"> //SelectedIndex
或者:
<ComboBox Text="{Binding xxx}">
八.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.设置文本框只能输入字母:
input:InputMethod.IsInputMethodEnabled="False"
2.初始英文输入:
InputMethod.PreferredImeState="Off"
十九、关键帧动画
<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 最大化不覆盖任务栏
this.MaxHeight = SystemParameters.WorkArea.Height; //在主窗体的构造函数中添加
二十一、string.Format
<TextBlock Text="{Binding Name,StringFormat=Student Name: {0}}" Margin="10 0"/>
二十二、多值绑定
<TextBlock VerticalAlignment="Center" Foreground="Green">
<TextBlock.Text>
<MultiBinding StringFormat = "{}{0} | {1}">
<Binding Path="TotalCounts" />
<Binding Path="MonthCounts" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>