[英]Accessing Child Element in Xaml Control Library
我在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访问矩形,但是它不能正常工作帮助我
给矩形起个名字
<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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.