我有一个wpf控件,它通过一个只读属性公开它的一个子项(从它的controlTemplate)。目前它只是一个clr属性,但我不认为这有什么区别。
我希望能够从正在实例化主控件的XAML中设置子控件的属性之一。(实际上,我想绑定到它,但我认为设置它是一个很好的第一步。)
下面是一些代码:
public class ChartControl : Control
{
public IAxis XAxis { get; private set; }
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
this.XAxis = GetTemplateChild("PART_XAxis") as IAxis;
}
}
public interface IAxis
{
// This is the property I want to set
double Maximum { get; set; }
}
public class Axis : FrameworkElement, IAxis
{
public static readonly DependencyProperty MaximumProperty = DependencyProperty.Register("Maximum", typeof(double), typeof(Axis), new FrameworkPropertyMetadata(20.0, FrameworkPropertyMetadataOptions.AffectsRender, OnAxisPropertyChanged));
public double Maximum
{
get { return (double)GetValue(MaximumProperty); }
set { SetValue(MaximumProperty, value); }
}
}
以下是在XAML中设置嵌套属性的两种方法(两者都不编译):
<!--
This doesn't work:
"The property 'XAxis.Maximum' does not exist in XML namespace 'http://schemas.microsoft.com/winfx/2006/xaml/presentation'."
"The attachable property 'Maximum' was not found in type 'XAxis'."
-->
<local:ChartControl XAxis.Maximum="{Binding Maximum}"/>
<!--
This doesn't work:
"Cannot set properties on property elements."
-->
<local:ChartControl>
<local:ChartControl.XAxis Maximum="{Binding Maximum}"/>
</local:ChartControl>
这是可能的吗?
如果没有它,我想我只需要公开主控件上绑定到子控件的dp(在模板中)。我想还不错,但我只是想避免主控件上的属性爆炸。
干杯。