我有一个 WPF 控件,它通过只读属性公开其子级之一(来自其 ControlTemplate)。目前它只是一个 CLR 属性,但我认为这没有任何区别。
我希望能够在实例化主控件的 XAML 中设置子控件的属性之一。 (实际上,我想绑定(bind)它,但我认为设置它是一个很好的第一步。)
这是一些代码:
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,并绑定(bind)到子控件(在模板中)。我想还不错,但我只是想避免主控件上的属性爆炸。
干杯。
最佳答案
您不能这样做...您可以通过绑定(bind)中的路径访问嵌套属性,但在定义属性值时则不能。
你必须做这样的事情:
<local:ChartControl>
<local:ChartControl.XAxis>
<local:Axis Maximum="{Binding Maximum}"/>
</local:ChartControl.XAxis>
</local:ChartControl>
关于wpf - 我可以使用 XAML 设置控件的嵌套属性(属性值的属性)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/834391/