控件背景:有多个button需要有背景图片,但是wpf自带的button并没有imagebutton,如何要实现button的背景图片,需要重写template,但是如果有N个button,那需要些N个button的template,很麻烦。
所以,就有自定控件的button产生
<Grid Margin="50"> <Grid.RowDefinitions> <RowDefinition Height="auto" /> <RowDefinition Height="auto" /> </Grid.RowDefinitions> <CustomControls:CommonButonn CustomText="Enable" BackgroundType="Enable" /> <CustomControls:CommonButonn CustomText="Disable" BackgroundType="Disable" Grid.Row="1" /> </Grid>
public class CommonButonn : Button { private ImageBrush _eBackground = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/MyCustomControls;component/Images/e_ok.png", UriKind.RelativeOrAbsolute))); private ImageBrush _dBackground = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/MyCustomControls;component/Images/d_ok.png", UriKind.RelativeOrAbsolute))); //Custom Button Label public string CustomText { get { return (this.Template.FindName("lbRoot", this) as Label).Content.ToString(); } set { (this.Template.FindName("lbRoot", this) as Label).Content = value; } } private string _backgroundType; public string BackgroundType { get { return _backgroundType; } set { _backgroundType = value; this.SetBackground(); } } public CommonButonn() { this.Init(); } private void Init() { ControlTemplate template = new ControlTemplate(); FrameworkElementFactory factory = new FrameworkElementFactory(typeof(Grid), "grdRoot"); // factory.SetValue(BackgroundProperty, this._backGround); //Set Label FrameworkElementFactory label_factory = new FrameworkElementFactory(typeof(Label), "lbRoot"); label_factory.SetValue(FontSizeProperty, 15.0); //this object value is not type int label_factory.SetValue(ForegroundProperty, Brushes.Black); label_factory.SetValue(HorizontalAlignmentProperty, HorizontalAlignment.Center); label_factory.SetValue(VerticalAlignmentProperty, VerticalAlignment.Center); label_factory.SetValue(FontFamilyProperty, new FontFamily("微软雅黑")); factory.AppendChild(label_factory); template.VisualTree = factory; this.Template = template; this.ApplyTemplate(); this.Width = 122; this.Height = 69; } private void SetBackground() { switch (this._backgroundType) { case "Enable": (this.Template.FindName("grdRoot", this) as Grid).Background = this._eBackground; break; case "Disable": (this.Template.FindName("grdRoot", this) as Grid).Background = this._dBackground; break; } } }
截图: