我有一个 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(在模板中)。我猜还不错,但我只是想避免主控件上的属性爆炸。
干杯。