以改变一个Button为例:
首先添加FrameworkElementFactory和Button的Content绑定:如果要放多个其他的控件,可以定义一个Grid把他们封装起来:不过最好能在XAML中实现,那样比较简单!
首先添加FrameworkElementFactory
- Button btn = new Button();
- //定义FrameworkElementFactory
- FrameworkElementFactory eleFactory = new FrameworkElementFactory(typeof(TextBlock), "TextBlock");
- TextBlock txb = new TextBlock();
- eleFactory.SetValue(TextBlock.HeightProperty, 22.0);
- eleFactory.SetValue(TextBlock.BackgroundProperty, Brushes.Gray);
- eleFactory.SetValue(TextBlock.TextAlignmentProperty, TextAlignment.Center);
- eleFactory.SetValue(TextBlock.VerticalAlignmentProperty, VerticalAlignment.Bottom);
- eleFactory.SetValue(TextBlock.FontFamilyProperty,new FontFamily("Arial"));
- Binding binding = new Binding();
- binding.Source = btn;
- binding.Mode = BindingMode.OneWay;
- binding.Path = new PropertyPath("Content", 0);
- eleFactory.SetBinding(TextBlock.TextProperty, binding);
- ControlTemplate ctrlTemplate = new ControlTemplate(typeof(Button));
- ctrlTemplate.VisualTree = eleFactory;
- btn.Template = ctrlTemplate;
- //显示内容1
- FrameworkElementFactory eleFac1 = new FrameworkElementFactory(typeof(Image), "Image");
- BitmapImage bitmap = new BitmapImage();
- bitmap.BeginInit();
- bitmap.UriSource = new Uri("路径");
- bitmap.EndInit();
- eleFac1.SetValue(Image.SourceProperty, bitmap);
- //显示内容2
- FrameworkElementFactory eleFac2= new FrameworkElementFactory(typeof(TextBox), "TextBox");
- eleFac2.SetValue(TextBox.WidthProperty,100.0);
- eleFac2.SetValue(TextBox.HeightProperty, 100.0);
- //把要呈现的显示内容封装起来
- FrameworkElementFactory fac = new FrameworkElementFactory(typeof(Grid), "Grid");
- fac.AppendChild(eleFac1);
- fac.AppendChild(eleFac2);