对象属性赋值
1、Attribute=Value形式
优点: 赋值方便。
缺点: Value为字符串,但是对象属性未必是字符串,因此无法赋太复杂的值。
示例:
- 绘制一个矩形,填充颜色并设置圆角;
- 绘制一个路径,将路径闭合并填充颜色;
<Window x:Class="WpfApplication2.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:WpfApplication2"
mc:Ignorable="d"
Title="选择" Height="300" Width="400">
<Grid>
<Rectangle Width="100" Height="30" Stroke="LightSalmon" Fill="LightCyan" RadiusY="5" RadiusX="5"/>
<Path Data="M 0,0 L 80,20 L 20,80 Z" Stroke="Black" Fill="LightGoldenrodYellow"/>
</Grid>
</Window>
效果如图所示:
2、属性标签
优点: 可以为对象属性赋较为复杂的值。
缺点: 程序量大(因此在允许条件下可部分采用Attribute=Value形式,或使用属性默认值)。
示例:
- 在按钮对象上绘制一个矩形并填充颜色;
- 在矩形对象中添加渐变色填充;
<Window x:Class="WpfApplication2.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:WpfApplication2"
mc:Ignorable="d"
Title="选择" Height="300" Width="400">
<Grid>
<!-- 按钮添加矩形 -->
<Button Width="100" Height="30" Background="LightCyan" Margin="0,0,200,200">
<Button.Content>
<Rectangle Width="20" Height="20" Fill="LawnGreen"/>
</Button.Content>
</Button>
<!--矩形渐变填充 -->
<Rectangle Width="150" Height="50">
<Rectangle.Fill>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
<LinearGradientBrush.GradientStops>
<GradientStop Offset="0.3" Color="LightGoldenrodYellow" />
<GradientStop Offset="0.7" Color="LightCoral" />
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
</Grid>
</Window>
效果如图所示:
3、标签扩展
标签扩展与Attribute=Value形式非常类似,只是后面Value的字符串格式比较特殊。
示例:
- 滑动一个滑块,在文本框内显示滑动的值。
<Window x:Class="WpfApplication2.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:WpfApplication2"
mc:Ignorable="d"
Title="选择" Height="300" Width="400" Background="LightCyan">
<Grid Margin="15">
<Grid.RowDefinitions>
<RowDefinition Height="24" />
<RowDefinition Height="4" />
<RowDefinition Height="24"/>
</Grid.RowDefinitions>
<TextBox x:Name="tb" Text="{Binding ElementName=sld, Path=Value}"/>
<Slider x:Name="sld" Grid.Row="2" Value="50" Maximum="200" Minimum="0"/>
</Grid>
</Window>
效果如图所示: