WPF关于C#代码实现Template

本文介绍了如何在WPF应用中利用C#代码动态创建并设置ControlTemplate,通过示例展示了为Button创建Template的过程,包括设置TextBlock属性、使用Binding绑定Content以及添加Image和TextBox元素到Grid中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值