如何在申请控制之前更改模板?

时间:2015-02-27 11:23:03

标签: c# wpf

我需要创建一个模板并将其应用于控件。 我有模板:

private string template = "<ControlTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' x:Key=\"simpleSlider\" TargetType=\"{x:Type Slider}\">"
         + "<Border SnapsToDevicePixels=\"true\" BorderBrush=\"{TemplateBinding BorderBrush}\" BorderThickness=\"{TemplateBinding BorderThickness}\">"
            + "<Grid>"
                + "<Grid.RowDefinitions>"
                    + "<RowDefinition Height=\"Auto\"/>"
                    + "<RowDefinition Height=\"Auto\" MinHeight=\"{TemplateBinding MinHeight}\"/>"
                    + "<RowDefinition Height=\"Auto\"/>"
                + "</Grid.RowDefinitions>"
                + "<Rectangle x:Name=\"PART_SelectionRange\"/>"
                + "<Track x:Name=\"PART_Track\" Grid.Row=\"1\">"
                    + "<Track.Thumb>"
                        + "<Thumb x:Name=\"Thumb\">"
                            + "<Thumb.Template>"
                                + "<ControlTemplate TargetType=\"Thumb\">"
                                    + "<Grid Name=\"grid\">"
                                        + "<Rectangle x:Name=\"slideRec\" Fill=\"Red\" Stroke=\"Black\" StrokeThickness=\"1\" Width=\"10\" Height=\"18\" SnapsToDevicePixels=\"True\"/>"
                                        + "<Label Content=\"{Binding Tag}\" Height=\"16\"/>"
                                    + "</Grid>"
                                + "</ControlTemplate>"
                            + "</Thumb.Template>"
                        + "</Thumb>"
                    + "</Track.Thumb>"
                + "</Track>"
            + "</Grid>"
        + "</Border>"
    + "</ControlTemplate>";

我需要以编程方式创建一个控件并应用模板来控制。 代码是:

        Slider slider = new Slider();
        slider.ValueChanged += slider_ValueChanged;
        slider.Tag = sliders.Count == 0 ? 0 : calcularPosicao(sliders, result);
        slider.Template = (ControlTemplate)XamlReader.Parse(this.template);
        slider.ApplyTemplate();

如何更改矩形的颜色填充? 要尝试在模板中查找de rectangle,请尝试以下操作:

var track = (Track)slider.Template.FindName("PART_Track", slider);

但结果为空。

1 个答案:

答案 0 :(得分:1)

根据您的目的而定。问题是,当您进入跟踪/拇指控制时,您添加的控件模板尚未应用,要执行您要执行的操作,您必须调用applytemplate()来获取您所使用的矩形寻找。

 var slider = new Slider();
 slider.Template = (ControlTemplate)XamlReader.Parse(template);
 slider.ApplyTemplate();
 var track = (Track)slider.Template.FindName("PART_Track", slider);
 var thumb = (Thumb)(track.FindName("Thumb") );
 thumb.ApplyTemplate(); // key here
 var rect = (Rectangle)thumb.Template.FindName("slideRec", thumb);
 rect.Fill = new SolidColorBrush(Colors.Blue);