Windows Phone 7自定义一个控件库跟Silverlight的是基本一样的,第一步创建一个类库,然后添加一个Themes文件夹,在文件夹里面添加上generic.xaml文件作为默认的控件样式文件,记住一定要写这个名字否则就找不到样式了,大小写都可以。新建一个控件类MyContro1.cs,MyContro2.cs在这里面就可以写控件的处理逻辑了。
下面看一下一个水印控件的处理:
generic.xaml文件
WatermarkTextBox..cs
using System.Windows; using System.Windows.Controls; namespace Phone.Controls { public class WatermarkedTextBox : TextBox { ContentControl WatermarkContent; public static readonly DependencyProperty WatermarkProperty = DependencyProperty.Register("Watermark", typeof(object), typeof(WatermarkedTextBox), new PropertyMetadata(OnWatermarkPropertyChanged)); public static readonly DependencyProperty WatermarkStyleProperty = DependencyProperty.Register("WatermarkStyle", typeof(Style), typeof(WatermarkedTextBox), null); public Style WatermarkStyle { get { return base.GetValue(WatermarkStyleProperty) as Style; } set { base.SetValue(WatermarkStyleProperty, value); } } public object Watermark { get { return base.GetValue(WatermarkProperty) as object; } set { base.SetValue(WatermarkProperty, value); } } public WatermarkedTextBox() { DefaultStyleKey = typeof(WatermarkedTextBox); } public override void OnApplyTemplate() { base.OnApplyTemplate(); this.WatermarkContent = this.GetTemplateChild("watermarkContent") as ContentControl; if(WatermarkContent != null) { DetermineWatermarkContentVisibility(); } } protected override void OnGotFocus(RoutedEventArgs e) { if (WatermarkContent != null && string.IsNullOrEmpty(this.Text)) { this.WatermarkContent.Visibility = Visibility.Collapsed; } base.OnGotFocus(e); } protected override void OnLostFocus(RoutedEventArgs e) { if (WatermarkContent != null && string.IsNullOrEmpty(this.Text)) { this.WatermarkContent.Visibility = Visibility.Visible; } base.OnLostFocus(e); } private static void OnWatermarkPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) { WatermarkedTextBox watermarkTextBox = sender as WatermarkedTextBox; if(watermarkTextBox != null && watermarkTextBox.WatermarkContent !=null) { watermarkTextBox.DetermineWatermarkContentVisibility(); } } private void DetermineWatermarkContentVisibility() { if (string.IsNullOrEmpty(this.Text)) { this.WatermarkContent.Visibility = Visibility.Visible; } else { this.WatermarkContent.Visibility = Visibility.Collapsed; } } } }