我可以使用XAML来设置控件的嵌套属性(属性值的属性)吗?

9
我有一个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(数据属性),然后将其绑定到子控件(在模板中)。我想也不错,但我只是想避免在主控件上出现大量的属性。

谢谢。

1个回答

5

你不能像这样做...你可以通过绑定路径访问嵌套属性,但是不能在定义属性值时这样做。

你需要这样做:

<local:ChartControl>
    <local:ChartControl.XAxis>
        <local:Axis Maximum="{Binding Maximum}"/>
    </local:ChartControl.XAxis>
</local:ChartControl>

是的,这正是我想的。:-(那么,额外的DP就在我的顶级控件上了! - Swythan
9
顺便说一句,我无法像您的 XAML 示例中那样操作,因为我不想用新的 Axis 实例替换 XAxis 属性的现有值。 - Swythan
2
我想知道WPF不支持绑定到嵌套属性的原因是什么?否则就会出现重复的情况。 - Vitalij

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接