问题
UPDATE 1
If ControlTemplate has binding, will XamlReader.Load(...)
work ?
<ControlTemplate TargetType="charting:LineDataPoint">
<Grid>
<ToolTipService.ToolTip>
<ContentControl Content="{Binding Value,Converter={StaticResource DateToString},ConverterParameter=TEST}"/>
</ToolTipService.ToolTip>
<Ellipse Fill="Lime" Stroke="Lime" StrokeThickness="3" />
</Grid>
</ControlTemplate>
I want to achieve this from code behind.
<ControlTemplate>
<Ellipse Fill="Green" Stroke="Red" StrokeThickness="3" />
</ControlTemplate>
I searched a lot all are showing FrameworkElementFactory
& VisualTree
property of ControlTemplate. These are not avaible in .NET for Windows Store Apps.
Anyone knows to create ControlTemplate
from code behind ?
回答1:
Try this:
private static ControlTemplate CreateTemplate()
{
const string xaml = "<ControlTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><Ellipse Fill=\"Green\" Stroke=\"Red\" StrokeThickness=\"3\" /></ControlTemplate>";
var сt = (ControlTemplate)XamlReader.Load(xaml);
return сt;
}
May be there is a more beautiful solution, but this sample works.
add: Don't forget include Windows.UI.Xaml.Markup namespace:
using Windows.UI.Xaml.Markup;
回答2:
from this link what i am getting is that controltemplate is belong to xaml part of the page because you can not alter them from simple run time Apis . yes thr may be way to do that but it is not recommended..
回答3:
You can define a Template part for your control, and then define a panel in your Template that you will be able to retrieve programmatically.
[TemplatePart(Name = "RootPanel", Type = typeof(Panel))]
public class TestControl : Control
{
private Panel panel;
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
panel = (Panel) GetTemplateChild("RootPanel");
panel.Children.Add(new Ellipse()
{
Fill = new SolidColorBrush(Colors.Green),
Stroke = new SolidColorBrush(Colors.Red),
StrokeThickness = 3,
VerticalAlignment =VerticalAlignment.Stretch,
HorizontalAlignment = HorizontalAlignment.Stretch
});
}
}
<ControlTemplate TargetType="local:TestControl">
<Grid x:Name="RootPanel" />
</ControlTemplate>
来源:https://stackoverflow.com/questions/17593999/how-to-create-controltemplate-from-code-behind-in-windows-store-app