观看刘铁猛老师视频的学习笔记
对象的赋值
1.attribute=value形式
<Botton Contet="show">
2.属性标签
使用标签赋值的方法为Button.Content赋值(不局限于string,可以是图片或其他东西)
<Button x:Name="test" Click="Button_Click" Width="70" Height="30" >
<Button.Content>
<Rectangle Width="20" Height="20" DataContext="暂停" Stroke="Black" Fill="GreenYellow"/>
</Button.Content>
</Button>
3.标签扩展
示例创建,为window创建String资源,通过标签扩展调用
<Window x:Class="MyWpfApp.MainWindow"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Title="MainWindow" Height="400" Width="600" WindowStartupLocation="CenterScreen">
<Window.Resources>
<sys:String x:Key="Hello">Hello WPF!</sys:String>
</Window.Resources>
<Grid>
<Button x:Name="test" Click="Button_Click" Width="70" Height="30" Content="{StaticResource Hello}"/>
</Grid>
</Window>
在xaml中实例化对象,对控件的事件作出响应,获取windons的资源
- 在cs文件中创建Human类
public class Human { public string Name; public Human Child; }
- xaml中引入实例化类的命名空间
xmlns:local ="clr-namespace:MyWpfApp"
- 创建windows资源,并为其赋值
<Window.Resources> <local:Human x:Key="Human" Name="Tim" /> </Window.Resources>
- 构建控件及挂载事件处理函数
<Button Content="show!" Click="Button_Click" Width="70" Height="30"/>
- 事件处理函数Button_Click,已经自动创建好了,转到定义进行实现
private void Button_Click(object sender, RoutedEventArgs e) { //1.将window的资源检索出来 Human h = this.FindResource("Human") as Human; if (h != null) { MessageBox.Show(h.Name); } }
xaml中赋值都是string的原理
- 对于新创建的类,如果成员不是String类型,在xaml中赋值是会报错的
<Window.Resources> <local:Human x:key="Human" Name="Tim" Child="LittleTim"> </Window.Resources>
- 使用TypeConverter作为基类,重写ConvertFrom方法
public class NameToHuamnTypeConverter : TypeConverter { //传入值object value就是xaml中写入的string public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { string name = value.ToString(); Human child = new Human(); child.Name = name; return child; } }
- 将新创建的类以特性的方式附加到Human类上去
[TypeConverterAttribute(typeof(NameToHuamnTypeConverter))] public class Human { public string Name; public Human Child; }
- 就可以进Human.child的赋值与使用了
滑动滑块TextBox显示当前滑块的值
使用Binding
<TextBox x:Name="b" Height="30" Margin="0,10,425.333,330.667" Text="{Binding ElementName=sli,Path=Value}"/>
<Slider x:Name="sli" Height="30" Margin="0,45,425.333,295.667" Grid.Row="2" Value="50" Minimum="0" Maximum="100"/>