【WP7】自定义控件
首先说说自定义控件
WP7自带的控件使用起来太过于单一,有时候我们需要自己自定义一些空间的行为或显示,下面演示自定义按钮控件,为新控件添加BackColor和ForeColor两个属性
1、新建一个类,定义两个属性 ForeColor 和 BackColor
public class MyButton : Button { public MyButton() { } public Color ForeColor { get { return ((SolidColorBrush)this.Foreground).Color; } set { this.Foreground = new SolidColorBrush(value); } } public Color BackColor { get { return ((SolidColorBrush)this.Background).Color; } set { this.Background = new SolidColorBrush(value); } } }
接下来是使用,在xaml页面中使用该控件,先添加命名空间
xmlns:local="clr-namespace:PhoneApp1"
<local:MyButton BackColor="Red" ForeColor="White" Content="Button" Height="72" x:Name="myButton1" Width="160" />
接下来将该属性作为资源样式Style来设置
<phone:PhoneApplicationPage.Resources> <Style x:Key="colorStyle1" TargetType="local:MyButton"> <Setter Property="BackColor" Value="Azure" ></Setter> <Setter Property="ForeColor" Value="Chartreuse" ></Setter> </Style> </phone:PhoneApplicationPage.Resources>
<local:MyButton Style="{StaticResource colorStyle1}" Content="Button" Height="72" x:Name="myButton1" Width="160" />
但是会报错
为什么呢,要想为自定义的属性使用Style,那么就必须将之设置为DependencyProperty
DependencyProperty的定义格式为
public static readonly DependencyProperty 变量名=
DependencyProperty.Register("属性名",
typeof(属性类型),
typeof(所属类的类型),
new PropertyMetadata(默认值, 值变化时触发的方法));
现在我们修改之前的代码,将ForceColor和BackColor设置为DependencyProperty,修改后的MyButton类如下
public class MyButton : Button { public MyButton() { } public Color ForeColor { get { return (Color)GetValue(ForeColorProperty); } set { SetValue(ForeColorProperty, value); } } public Color BackColor { get { return (Color)GetValue(BackgroundProperty); } set { SetValue(BackgroundProperty, value); } } public static readonly DependencyProperty BackColorProperty = DependencyProperty.Register("BackColor", typeof(Color), typeof(MyButton), new PropertyMetadata(Colors.Blue, OnColorChanged)); public static readonly DependencyProperty ForeColorProperty = DependencyProperty.Register("ForeColor", typeof(Color), typeof(MyButton), new PropertyMetadata(Colors.Red, OnColorChanged)); private static void OnColorChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) { MyButton btn = obj as MyButton; if (e.Property == ForeColorProperty) { btn.Foreground = new SolidColorBrush((Color)e.NewValue); } if (e.Property == BackColorProperty) { btn.Background = new SolidColorBrush((Color)e.NewValue); } } }
然后设置资源
<phone:PhoneApplicationPage.Resources> <Style x:Key="colorStyle1" TargetType="local:MyButton"> <Setter Property="BackColor" Value="BlueViolet" ></Setter> <Setter Property="ForeColor" Value="Red" ></Setter> </Style> </phone:PhoneApplicationPage.Resources>
<local:MyButton Style="{StaticResource colorStyle1}" Content="Button" Height="72" x:Name="myButton1" Width="160" />
但是,在设计视图中,不能看到效果