我可以使用 XAML 设置控件的嵌套属性(属性值的属性)吗? [英] Can I use XAML to set a nested property (property of the value of a property) of a control?

查看:14
本文介绍了我可以使用 XAML 设置控件的嵌套属性(属性值的属性)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 WPF 控件,它通过只读属性公开它的一个子项(来自它的 ControlTemplate).目前它只是一个 CLR 属性,但我认为这没有任何区别.

I've got a WPF Control that exposes one of it's children (from it's ControlTemplate) through a read-only property. At the moment it's just a CLR property, but I don't think that makes any difference.

我希望能够从我正在实例化主控件的 XAML 中设置子控件的属性之一.(实际上,我想绑定到它,但我认为设置它是一个很好的第一步.)

I want to be able to set one of the properties on the child control from the XAML where I'm instantiating the main control. (Actually, I would like to bind to it, but I think setting it would be a good first step.)

这是一些代码:

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 中设置嵌套属性的两种方法(均不编译):

Here's the two ways I can think of setting the nested property in XAML (neither compile):

<!-- 
    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 来绑定到子控件(在模板中).我想还不错,但我只是想避免主控件上的属性爆炸.

Without it I guess I'll just need to expose DP's on the main control that get bound through to the children (in the template). Not so bad, I guess, but I was just trying to avoid an explosion of properties on the main control.

干杯.

推荐答案

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

You can't do it like this... you can access nested properties through its path in a binding, but not when you define the value of the property.

你必须这样做:

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

这篇关于我可以使用 XAML 设置控件的嵌套属性(属性值的属性)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆