2014-02-20 25 views
1

我正在一個xaml文件(library.xaml)中創建一個控制庫,其中我已經定義了所有控件,並在即將處理其名爲(library.cs)的.cs文件中處理它們的事件 要訪問資源字典的子元素在cs文件...我天璣KNW怎麼做在Xaml控制庫中訪問子元素

這裏是我的兩個文件

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

有一些名字您的矩形,

<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 
} 
+0

我已經嘗試過這一點,但我爲獲得該「名模板不當前環境的存在」的錯誤。有沒有其他的方式來訪問它? – Ravi

+0

您是否在控件加載過程中嘗試過? – Sankarann

+0

正如我之前提到的我不想使用事件和事件處理程序 – Ravi