我有一个WPF控件,它通过只读属性公开了其ControlTemplate中的一个子元素。目前它只是一个CLR属性,但我认为这没有任何区别。
我想能够从实例化主控件的XAML中设置子控件的属性。(实际上,我想绑定到它,但我认为先设置它是一个好的第一步。)
以下是一些代码:
我想能够从实例化主控件的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(数据属性),然后将其绑定到子控件(在模板中)。我想也不错,但我只是想避免在主控件上出现大量的属性。
谢谢。