This commit is contained in:
sherlockforrest
2023-06-20 09:22:53 +08:00
commit bf2ed2e31f
621 changed files with 271599 additions and 0 deletions

34
WPF/AttachedProperty.md Normal file
View File

@@ -0,0 +1,34 @@
# 释义
本不属于某个对象的属性,在被需要的时候后来附加;在特定环境下对象才具有的属性如当一个控件在Grid中时会附加Grid.Column属性等
本质上是依赖属性
用clr属性包装时不同是采用两个方法
```csharp
public static int GetMyProperty(DependencyObject obj)
{
return (int)obj.GetValue(MyPropertyProperty);
}
public static void SetMyProperty(DependencyObject obj, int value)
{
obj.SetValue(MyPropertyProperty, value);
}
// Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.RegisterAttached("MyProperty", typeof(int), typeof(ownerclass), new PropertyMetadata(0));
```
把年级附加属性附加给人
```csharp
class Human:DependencyObject
{
}
Human human=new Human()
School.SetMyProperty(human,6)//设置属性
int grade=School.GetMyProperty(human)//得到属性值
```

184
WPF/Binding.md Normal file
View File

@@ -0,0 +1,184 @@
# 绑定方向及数据更新
Path 绑定属性名称Source 绑定数据源,绑定属性必须是依赖属性
UpdateSourceTrigger 更新源触发器
PropertyChanged LostFocus Explicit Default
可以用控件.SetBinding(控件静态属性,new Binding("Path")){Source=xxx}
如果绑定的集合类的属性仍然是集合,可以用'/'将子集集合中的元素当作Path
绑定属性可以为控件静态属性 Path=Text.Length;
Source本身就代表数据如字符串的时候Path可以省略只留下Binding或Binding Path=.或Binding .
Binding的源类型Source
- clr类型对象
- clr集合对象ItemsSource
- ADO.Net数据对象 DataTable DataViewDataTable.DefaultView;
ListView派生与ListBoxGridView继承ViewBaseListView.View是ViewBase类型。目前ListView.View只能用GridView。
- XmlDataProvider XML数据TreeView MenuXmlDataProvider.Source=new Urine(@"路径")XPath=(要提取的节点,如/StudentList/Student);可以作为资源把xml内容放在<x:XData>标签内;
- 依赖对象 Dependency Object 可以作为源和目标依赖对象的依赖属性作为Path
- 容器DataContext上下文数据源,依赖属性无法明确是从哪个源的属性获取数据时它上层的DataContext会沿着UI树往下传递直到找到源中有对应Path的属性后将该DataContext作为自己的源
DataContext使用场景
a. 当UI上的多个控件使用Binding关注同一个对象时
b. 当Source对象不能被直接访问时如PrivateB窗口访问A窗口的控件时将A窗口的控件作为数据源时可以使用把控件作为窗口A的DataContextpublic暴露数据。
- ELementName=控件名
- RelativeSource属性相对地指定Source
RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type Grid},AncestorLevel=1},Path=Name}
RelativeSourceMode枚举:
FindAncestor查找父级TemplatedParent,PreviousData;
AncestorType父级类型AncestorLevel层级便宜量上一级为1三个美剧
- ObjectDataProvider
```csharp
ObjectDataProvider odp=new ObjectDataProvider()
odp.ObjectInstance=new Class();
odp.MethodName="方法名"
odp.MethodParameters.Add("参数值")
Binding bindingToArg1=new Binding("MethodParameters[0]")
{
Source=odp,
BindsDirectlyToSource=true,
UpdateSourceTrigger=UpdateSourceTrigger.PropertyChanged
}
Binding bindingToResult=new Binding("."){Source=odp}
//关联
.SetBinding(,bindingToArg1)
.SetBinding(,bindingToResult)
```
- Linq检索得到的数据对象
```csharp
XDocument xdoc=XDocument.Load();
from element in xdoc.Descendants("节点名称")
where element.Attribute("特性").Value....
select new Class()//转实例
{
}
```
# 数据校验
```csharp
public class RangeValidationRule:ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
double d=0;
if (double.TryParse(value.ToString(),out d))
{
if(d>=0&&d<=100>)
{
return new ValidationResult(true,null);
}
}
return new ValidationResult(false,"Validation Failed");
}
}
public Window(){
InitializeComponent();
Binding binding=new Binding("Value"){Source=this.slider}
binding.UpdateSourceTrigger=UpdateSourceTrigger.PropertyChanged
RangeValidationRUle rvr=new RangeValidationRUle()
rvr.ValidatesOnTargetUpdated=true//校验源数据
binding.ValudationRules.Add(rvr)
binding.NotifyOnValidationError=true;//校验错误,发出通知
this.textBox.SetBinding(TextBox.TextProperty,binding)
}
void ValidationError(object sender,RoutedEventArgs e){
if(Validation.GetErrors(this.textBox).Count>0)
{
this.textBox.ToolTip=Validation.GetErrors(this.textBox)[0].ErrorContent.ToString()
}
}
```
数据转换
```csharp
public class CategoryToSourceConverter:IValueConverter
{
//源=>目标(控件)
public object Converter(object value,Type targetType,object parameter,CultureInfo culture)
{
Category c=(Category)value;
switch(c)
{
case Category.Bomber:
return @"Icon/Bomber.png";
case Category.Fighter:
return @"Icon/Fighter.png";
Default:
return null;
}
}
public object ConvertBack(object value,Type targetType,object parameter,CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class StateToNullableBoolConverter:IValueConverter
{
//源=>目标(控件)
public object Converter(object value,Type targetType,object parameter,CultureInfo culture)
{
State s=(State)value;
switch(s)
{
case State.Locked:
return false;
case State.Available:
return true;
default:
return null;
}
}
public object ConvertBack(object value,Type targetType,object parameter,CultureInfo culture)
{
bool? nb=(bool?)value
switch(nb)
{
case false:
return State.Locked;
case true:
return State.Available;
default:
return State.Unknown;
}
}
}
```
```xaml
<Window.Resources>
<localCategoryToSourceConverter x:Key="cts"/>
<localStateToNullableConverter x:Key="stnb"/>
</Window.Resources>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Path=Category,Converter={StaticResource cts}}">//绑定
<CheckBox IsThreeState="True" IsCheck="{Binding Path=State,Converter={StaticResource stnb}}">
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
```
MultBinding使用场景一需要通过多个对象属性综合进行判断时;
Binding b1=new Binding("Text){Source=this.textBox1}
Binding b1=new Binding("Text){Source=this.textBox2}
MulitBinding mb=new MulitBinding(){Mode=Binding.OneWay}
mb.Bindings.Add(b1)//注意绑定顺序
mb.Bindings.Add(b2)
mb.Converter=LoginMultiBindingConverter()
this.btn.SetBinding(Button.IsEnabledProperty,mb)
public class LogoMultiBindingConverter: IMultiValueConverter
{
}

38
WPF/DependencyProperty.md Normal file
View File

@@ -0,0 +1,38 @@
# 依赖属性
- 节省实例对内存的开销
- 属性值可以通过Binding依赖在其他对象上
- 本身没有值依赖Binding数据源获取值
- 依赖属性需要依托依赖对象作为宿主
- WPF的所有控件均是依赖对象绝大多数属性也均为依赖属性
定义依赖属性
DependencyProperty是一种类型所有的依赖属性都是这个类型并且被public static readonly
```csharp
public class Student:DependencyObject
{
public static readonly DependencyProperty NameProperty=DependencyProperty.Register("Name",typeof(string),typeof(Student))
//PropertyMetadata
//CoerceValueCallback 依赖属性值被强制改变,调用此委托,关联一个影响函数
//DefaultValue 依赖属性未被显式赋值时,若读取则获取此默认值,不设置会抛出异常
//IsSealed 控制该数值是否可以更改默认true
//PropertyChangedCallback依赖属性的值被改变后此委托被调用关联一个影响函数
//clr属性包装依赖属性
public string Name
{
get{return (string)GetValue(NameProperty)}
Set{SetValue(NameProperty,value)}
}
public BindingExpressionBase SetBinding(DependencyProperty dp,BindingBase binding)
{
return BindingOperations.SetBinding(this,dp,binding)
}
}
Student stu=new Student()
stu.SetValue(Student.NameProperty,this.textBox.Text)
textBox1.Text=(string)stu.GetValue(Student.NameProperty)
```

3
WPF/ItemControls.md Normal file
View File

@@ -0,0 +1,3 @@
SelectedValuePath绑定为属性
SelectedValue绑定为对象与SelectedValuePath配套使用
SelectedValue与SelectedItem一般情况下是一样的

68
WPF/MahappsWindow.xaml Normal file
View File

@@ -0,0 +1,68 @@
<Window
x:Class="MahappsWindow"
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:ui="http://schemas.modernwpf.com/2019"
Title="MahappsWindow"
Width="800"
Height="800"
mc:Ignorable="d">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<!--<ui:XamlControlsResources />-->
<ui:ColorPaletteResources Accent="#FF0078D7" TargetTheme="Light" />
<ResourceDictionary Source="pack://application:,,,/ModernWpf;component/ThemeResources/Light.xaml" />
<ResourceDictionary Source="pack://application:,,,/ModernWpf;component/ControlsResources.xaml" />
<!--<ui:ThemeResources CanBeAccessedAcrossThreads="True" RequestedTheme="Light" />
<ui:XamlControlsResources UseCompactResources="True" />-->
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<ui:SimpleStackPanel Margin="12" Spacing="10">
<TextBlock Style="{StaticResource HeaderTextBlockStyle}" Text="My first ModernWPF app" />
<Button Content="I am a button" />
<Button Content="I am an accent button" Style="{StaticResource AccentButtonStyle}" />
<DatePicker />
<TreeView d:ItemsSource="{d:SampleData}" />
<TextBox Style="{StaticResource DefaultTextBoxStyle}" Text="TextBox" />
<ComboBox Text="选择">
<ComboBoxItem Content="FistItem" />
<ComboBoxItem Content="SecondItem" />
</ComboBox>
<DataGrid d:ItemsSource="{d:SampleData}" />
</ui:SimpleStackPanel>
<ui:SimpleStackPanel Grid.Column="1">
<ui:NumberBox
Description="数字框"
Header="数字框"
LargeChange="10"
Maximum="100"
Minimum="10"
PlaceholderText="数字"
SmallChange="5"
SpinButtonPlacementMode="Inline"
ValidationMode="InvalidInputOverwritten" />
<ui:ToggleSwitch
IsOn="True"
OffContent="关闭"
OnContent="开启" />
<ui:AutoSuggestBox />
<ui:RadioButtons d:ItemsSource="{d:SampleData}" Header="RadioButton" />
<ui:ToggleSplitButton />
<ui:NavigationView AlwaysShowHeader="True" Header="展开">
<ui:NavigationViewItem Content="项目一" />
</ui:NavigationView>
<!--<Calendar />-->
<ToggleButton Content="ToggleButton" />
<ui:DropDownButton UseSystemFocusVisuals="True" />
</ui:SimpleStackPanel>
</Grid>
</Window>

12
WPF/MahappsWindow.xaml.cs Normal file
View File

@@ -0,0 +1,12 @@
using System.Windows;
/// <summary>
/// MahappsWindow.xaml 的交互逻辑
/// </summary>
public partial class MahappsWindow : Window
{
public MahappsWindow()
{
InitializeComponent();
}
}

14
WPF/Markup Extension.md Normal file
View File

@@ -0,0 +1,14 @@
# 标记扩展
MarkupExtension派生类才能使用
可以嵌套
属性值不再加引号
```xaml
<TextBox Text="{Binding ElementName=slider,Path=Vaule,Mode=OneWay}"/>
```
```csharp
Binding binding=new Binding(){source=slider,Mode=OneWay};
```

9
WPF/Rectangle.md Normal file
View File

@@ -0,0 +1,9 @@
# Brush
Brush Retangle.Fill
SolidColorBrush:单色画刷
LinerarGradientBuilder:线性渐变画刷
RadialGradientBrush:径向渐变画刷
ImageBrush:位图画刷
DrawingBrush:矢量图画刷
VisualBrush:可视元素画刷

32
WPF/TypeConvert.md Normal file
View File

@@ -0,0 +1,32 @@
# 类型转换
```csharp
[typeconvert(typeof(stringtohumanTypeConvert))]
public class Human
{
public string Name {get; set; }
public Human Child {get; set; }
}
```
```xaml
<windows.resource>
<local:Human x:key="human" Child="ABC"/>
</windows.resource>
```
```csharp
public class stringtohumanTypeConvert:typeconvert
{
public override object convertfrom(Itypedescriptioncontext context,system.globalization.culture.CultureInfo culture,object value)
{
if(value is string)
{
Human h=new Human();
h.Name=value as string;
return h;
}
return base.convertfrom(context, culture,value);
}
}
```

16
WPF/VaildationRules.md Normal file
View File

@@ -0,0 +1,16 @@
```xaml
<TextBox.Text>
<Binding Path="FloorHeight" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<valrules:RangeVaildationRule Max="100" Min="0" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
```
```xaml
<Window.DataContext>
<local:FloorFinshesViewModel />
</Window.DataContext>
```

17
WPF/Wpf-Ui.cs Normal file
View File

@@ -0,0 +1,17 @@
private Collection<ResourceDictionary> GetAllDictionaries()
{
//TODO:修改此处以在中调用,因为Revit application会为空字体文件的生成方式应为资源
var application = Application.Current;
if (application != null)
{
return Application.Current.Resources.MergedDictionaries;
}
return new Collection<ResourceDictionary>();
}
static TextBlock()
{
//TODO 字体太大会修改界面字体Revit
TextElement.FontSizeProperty.OverrideMetadata(typeof(System.Windows.Controls.TextBlock), new FrameworkPropertyMetadata(14.0));
}

139
WPF/Wpf.Ui.xaml Normal file
View File

@@ -0,0 +1,139 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!--#region Wpf-Ui-->
<!-- xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml" -->
<!--<Style
x:Key="StandardFluentWindowStyle"
BasedOn="{StaticResource {x:Type Window}}"
TargetType="{x:Type ui:FluentWindow}">
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="{DynamicResource ApplicationBackgroundColor}" />
</Setter.Value>
</Setter>
<Setter Property="Foreground">
<Setter.Value>
<SolidColorBrush Color="{DynamicResource TextFillColorPrimary}" />
</Setter.Value>
</Setter>
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Height" Value="600" />
<Setter Property="MinHeight" Value="320" />
<Setter Property="Width" Value="1100" />
<Setter Property="MinWidth" Value="460" />
<Setter Property="Margin" Value="0" />
<Setter Property="Padding" Value="0" />
<Setter Property="FontSize" Value="{DynamicResource ControlContentThemeFontSize}" />
<Setter Property="FontWeight" Value="Normal" />
<Setter Property="UseLayoutRounding" Value="True" />
<Setter Property="SnapsToDevicePixels" Value="True" />
<Setter Property="OverridesDefaultStyle" Value="True" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Window}">
<Grid Background="{TemplateBinding Background}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<ui:TitleBar AllowDrop="True" />
<AdornerDecorator Grid.Row="1">
<ui:ClientAreaBorder
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ContentPresenter x:Name="ContentPresenter" />
</ui:ClientAreaBorder>
</AdornerDecorator>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="WindowState" Value="Normal">
<Setter Property="ResizeMode" Value="CanResize" />
</Trigger>
<Trigger Property="WindowState" Value="Maximized">
<Setter Property="ResizeMode" Value="NoResize" />
</Trigger>
</Style.Triggers>
</Style>
<Style BasedOn="{StaticResource StandardFluentWindowStyle}" TargetType="ui:FluentWindow">
<Setter Property="FontFamily" Value="Microsoft YaHei UI" />
<Setter Property="ShowInTaskbar" Value="True" />
</Style>
<Style BasedOn="{StaticResource {x:Type ContextMenu}}" TargetType="ContextMenu">
<Setter Property="FontFamily" Value="Microsoft YaHei UI" />
</Style>
<Style BasedOn="{StaticResource DefaultTextBoxStyle}" TargetType="TextBox">
<Setter Property="Margin" Value="5" />
</Style>
<Style BasedOn="{StaticResource DefaultUiTextBoxStyle}" TargetType="ui:TextBox">
<Setter Property="Margin" Value="5" />
</Style>
<Style BasedOn="{StaticResource DefaultUiNumberBoxStyle}" TargetType="ui:NumberBox">
<Setter Property="Margin" Value="5" />
<Setter Property="MaxDecimalPlaces" Value="0" />
</Style>
<Style BasedOn="{StaticResource DefaultButtonStyle}" TargetType="Button">
<Setter Property="Margin" Value="5" />
<Setter Property="FontFamily" Value="Microsoft YaHei UI" />
<Setter Property="HorizontalAlignment" Value="Stretch" />
</Style>
<Style BasedOn="{StaticResource {x:Type TextBlock}}" TargetType="TextBlock">
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="5" />
</Style>
<Style BasedOn="{StaticResource {x:Type Slider}}" TargetType="Slider">
<Setter Property="VerticalAlignment" Value="Bottom" />
<Setter Property="Margin" Value="5" />
<Setter Property="TickFrequency" Value="5" />
<Setter Property="TickPlacement" Value="BottomRight" />
<Setter Property="IsSelectionRangeEnabled" Value="True" />
</Style>
<Style BasedOn="{StaticResource DefaultDataGridStyle}" TargetType="DataGrid">
<Setter Property="Margin" Value="5" />
</Style>
<Style BasedOn="{StaticResource DefaultDataGridCellStyle}" TargetType="DataGridCell">
<Setter Property="Margin" Value="5" />
</Style>
<Style BasedOn="{StaticResource {x:Type GroupBox}}" TargetType="GroupBox">
<Setter Property="Margin" Value="5" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<Style BasedOn="{StaticResource DefaultComboBoxStyle}" TargetType="ComboBox">
<Setter Property="Margin" Value="5" />
</Style>
<Style BasedOn="{StaticResource DefaultRadioButtonStyle}" TargetType="RadioButton">
<Setter Property="Margin" Value="5" />
</Style>
<Style BasedOn="{StaticResource DefaultCheckBoxStyle}" TargetType="CheckBox">
<Setter Property="Margin" Value="5" />
</Style>
<Style BasedOn="{StaticResource {x:Type Label}}" TargetType="Label">
<Setter Property="Margin" Value="5" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<Style BasedOn="{StaticResource {x:Type TabControl}}" TargetType="TabControl">
<Setter Property="Margin" Value="5" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<Style BasedOn="{StaticResource DefaultListBoxStyle}" TargetType="ListBox">
<Setter Property="Margin" Value="5" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Cursor" Value="Hand" />
</Style>
<Style BasedOn="{StaticResource DefaultListViewStyle}" TargetType="ListView">
<Setter Property="Margin" Value="5" />
</Style>-->
<!--#endregion-->
</ResourceDictionary>

19
WPF/x Namespace.md Normal file
View File

@@ -0,0 +1,19 @@
# 修改Window窗口的作用域
x:ClassModifier
# 修改控件对象
x:FieldModifier x:Name必须声明
# 声明资源对象Window.Resources变量名
x:Key
# 获取同一个资源对象
x:Shared
# 数据类型
x:Type

10
WPF/分支.md Normal file
View File

@@ -0,0 +1,10 @@
## Properties分支
程序用到的资源,图标、图片、静态的字符串、配置信息
## References分支
.Net Framework类库、项目引用、Nuget包
App.xaml 声明主进程,主窗体