访问Xaml控件库中的子元素

时间:2014-02-20 11:55:24

标签: c# wpf xaml visual-studio-2012 controltemplate

我正在xaml文件(library.xaml)中创建一个控件库,我在其中定义了所有控件,并在名为(library.cs)的.cs文件中处理它们的事件 我想在.cs文件中访问资源字典的子元素...我知道如何做到这一点

这是我的两个文件

library.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                x:Class="custom_template.library">

 <Style  x:Key="my_progressbar_primary">
  <Setter Property="Control.Template">
   <Setter.Value>
    <ControlTemplate TargetType="ProgressBar" >
        <Grid Height="{TemplateBinding Height}" Width="{TemplateBinding Width}">
                    <Rectangle  HorizontalAlignment="Left" Height="20px"   VerticalAlignment="Top" Width="{TemplateBinding Width}"  Stroke="#ddd"  ClipToBounds="True" RadiusX="3" RadiusY="3" Style="{StaticResource style_shadow_top}"></Rectangle>
                    <Rectangle  Height="20" Width="100"   HorizontalAlignment="Left" VerticalAlignment="Top" RadiusX="3" RadiusY="3" Style="{StaticResource style_shadow_top_primary}"></Rectangle>
         </Grid>
    </ControlTemplate>
   </Setter.Value>
  </Setter>
</Style>
</ResourceDictionary>

library.cs

using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Timers;

  namespace custom_template
  {
   partial class library
   {
    private void xxx()
    {

    }
   }
 }

问题:我想在xxx()方法中更改矩形的宽度.....但我无法访问它...我也尝试使用findname访问矩形但它不起作用 帮助我

1 个答案:

答案 0 :(得分:-1)

为您的矩形命名,

<Rectangle x:Name="rect"  HorizontalAlignment="Left" Height="20px"   VerticalAlignment="Top" Width="{TemplateBinding Width}"  Stroke="#ddd"  ClipToBounds="True" RadiusX="3" RadiusY="3" Style="{StaticResource style_shadow_top}"></Rectangle>

并在库类中执行以下操作,

private void xxx()
{
     if (Template != null)
     {
         var rect = (Rectangle)Template.FindName("rect", this);
         //Where this is the Instance of ProgressBar.
         //check the rect is not null and change the width of rect here... 
     }
}

<强>更新

In your `OnApplyTemplate` of your custom control..

protected override void OnApplyTemplate()
{
    RectProperty = GetTemplateChild("rect") as Rectangle;
    //RectProperty is your property
}