Har*_*san 30 c# wpf xaml contentcontrol
我在XAML中有这个
<ControlTemplate TargetType="{x:Type Button}">
<Image ...>
</ControlTemplate>
Run Code Online (Sandbox Code Playgroud)
我希望在C#代码中实现相同的功能.我怎样才能做到这一点?
ControlTemplate ct = new ControlTemplate();..
Image img = new Image();..
Run Code Online (Sandbox Code Playgroud)
现在如何将此图像分配给控制模板?我们能做到这一点还是我错过了这里的概念?
H.B*_*.B. 29
在代码隐藏中创建模板不是一个好主意,理论上可以通过定义ControlTemplate.VisualTree哪个是a来实现FrameworkElementFactory.
ControlTemplate template = new ControlTemplate(typeof(Button));
var image = new FrameworkElementFactory(typeof(Image));
template.VisualTree = image;
Run Code Online (Sandbox Code Playgroud)
分配属性非常迂回,因为您需要使用SetValue和SetBinding:
image.SetValue(Image.SourceProperty, ...);
Run Code Online (Sandbox Code Playgroud)
此外,关于(以前)接受的答案和引用的东西:
以编程方式设置ControlTemplate就像使用XAML一样,因为我们必须使用XamlReader类.
那句话是错的,我们不"必须".
如果我在运行时分配模板,我将它们定义为一个资源,如果我需要它我可以加载.
编辑:根据文档FrameworkElementFactory不推荐使用:
此类是以编程方式创建模板的不推荐使用的方式,模板是FrameworkTemplate的子类,如ControlTemplate或DataTemplate; 使用此类创建模板时,并非所有模板功能都可用.以编程方式创建模板的推荐方法是使用XamlReader类的Load方法从字符串或内存流加载XAML.
我想知道这个建议是不是一个好主意.我个人仍然会将模板定义为XAML中的资源,如果我可以避免使用字符串和XamlReader.
obe*_*iro 23
以编程方式设置ControlTemplate就像使用XAML一样,因为我们必须使用XamlReader类.例如,这里是设置按钮模板的代码,假设我们想要在加载后设置按钮的模板.
private void Button_Loaded(object sender, RoutedEventArgs e) {
var button = sender as Button;
string template =
"<ControlTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
TargetType=\"Button\">" +
"<Border>" +
"<ContentPresenter/>" +
"</Border>" +
"</ControlTemplate>";
button.Template = (ControlTemplate)XamlReader.Parse(template);
}
Run Code Online (Sandbox Code Playgroud)
由于我们使用字符串来指定模板的XAML代码,因此我们可以使用XamlReader的Parse方法.XamlReader还有一个Load方法,主要用于流或XAML或XML读取器.请注意,我们必须包含XML命名空间 http://schemas.microsoft.com/winfx/2006/xaml/presentation, 因为我们需要在那里定义ControlTemplate,Border和其他控件.如果我们不包含它,我们将遇到运行时异常.基本上,我们必须放置模板所需的名称空间.
| 归档时间: |
|
| 查看次数: |
47394 次 |
| 最近记录: |