用户控件
创建用户控件可以在项目里右键添加用户控件,用户控件可以解决系统没有这个控件自己可以特定制作这个控件供自己项目中使用 或者 如果很多地方用到某到模块,就可以把这个模块封装成用户控件供多出调用
下面创建一个用户控件:
<UserControl x:Class="用户控件.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="124" d:DesignWidth="109" > <Grid Height="128" Width="113"> <Border BorderThickness="2" Margin="0,0,1,1"> <Border.BorderBrush> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Offset="0" Color="#aaa"/> <GradientStop Offset="1" Color="#222"/> </LinearGradientBrush> </Border.BorderBrush> <Canvas PreviewMouseLeftButtonDown="Canvas_PreviewMouseLeftButtonDown" Height="113" Width="96"> <Image x:Name="imageCar" Width="96" Height="113"/> <Image Height="24" HorizontalAlignment="Left" Margin="91,147,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="29" Canvas.Left="-24" Canvas.Top="-59" Visibility="Hidden" /> </Canvas> </Border> </Grid> </UserControl>
将图片封装到一个带有边框的Border中
后台代码:
/// <summary> /// UserControl1.xaml 的交互逻辑 /// </summary> public partial class UserControl1 : UserControl { public UserControl1() { InitializeComponent(); this.ImagePath = "/Resources/奔驰.png"; this.image1.Source = new BitmapImage(new Uri(@"/Resources/打勾.jpg", UriKind.Relative)); } private void Canvas_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (image1.Visibility == Visibility.Visible) { image1.Visibility = Visibility.Hidden; } else { image1.Visibility = Visibility.Visible; } } public string ImagePath { get; set; } public void setImage() { //imageCar.Source = ImagePath this.imageCar.Source = new BitmapImage(new Uri(@ImagePath,UriKind.Relative)); } }
添加到Window界面上
Window x:Class="用户控件.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="450" Width="616" xmlns:my="clr-namespace:用户控件"> <Grid> <my:UserControl1 HorizontalAlignment="Left" Margin="22,30,0,0" x:Name="userControl11" VerticalAlignment="Top"/> </Grid> </Window>
/// <summary> /// UserControl1.xaml 的交互逻辑 /// </summary> public partial class UserControl1 : UserControl { public UserControl1() { InitializeComponent(); this.ImagePath = "/Resources/奔驰.png"; } private void Canvas_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (image1.Visibility == Visibility.Visible) { image1.Visibility = Visibility.Hidden; } else { image1.Visibility = Visibility.Visible; } } public string ImagePath { get; set; } public void setImage() { //imageCar.Source = ImagePath this.imageCar.Source = new BitmapImage(new Uri(@ImagePath,UriKind.Relative)); } }