从XAML访问间接属性 - WPF

问题描述 投票:1回答:2

我有一个名为MyControl的Control类,它有直接的bool属性AccessDirectProperty和一个Object MyControlSettings

    public class MyControl : Control
    {
        public bool AccessDirectProperty
        {
            get; set;
        }
        public MyControlSettings ControlSettings
        {
            get;set;
        }
    }

请找到MyControlSettings类的详细信息

public class MyControlSettings
{
    public bool AccessIndirectProperty
    {
        get;set;
    }
}

可以从XAML访问Direct属性AccessDirectProperty而不会出现任何错误。

<Window>
    <Grid>
        <local:MyControl AccessDirectProperty="True"/>
    </Grid>
</Window>

但我无法从XAML中的对象ControlSettings访问属性AccessIndirectProperty。以下代码无法做到这一点。

<Window>
    <Grid>
        <local:MyControl AccessDirectProperty="True" ControlSettings.AccessIndirectProperty=""/>
    </Grid>
</Window>

谁可以帮我这个事?

c# wpf xaml binding dependency-properties
2个回答
0
投票

现在,在技术层面上,以下内容对修改通过MyControl.ControlSettings提供的现有MyControlSettings实例的属性没有用。但是,如果您的用例允许创建并将全新的MyControlSettings实例分配给MyControl.ControlSettings,则可以在XAML中执行此操作:

<local:MyControl>
    <ControlSettings>
        <local:MyControlSettings AccessIndirectProperty="true" />
    </ControlSettings>
</local:MyControl>

旁注:术语“ControlSettings”向我建议您想要某种MyControlSettings“容器”中的“打包”控件设置/属性。现在,我不知道为什么以及它的动机是什么,但请记住,选择这种方法会使得以一种有意义的方式使用数据绑定非常困难甚至不可能这样的设置属性应该是绑定目标。如果你想能够将个别设置用作绑定目标(如AccessIndirectProperty="{Binding Path=Source}"),我宁愿建议你的MyControl将这些设置单独公开为DependencyProperties


2
投票

我担心XAML不支持访问“嵌套”属性。

但是,您可以使ControlSettings成为attached properties的独立班级:

public class ControlSettings : DependencyObject
{
    public static readonly DependencyProperty AccessIndirectPropertyProperty =
        DependencyProperty.RegisterAttached(
              "AccessIndirectProperty", typeof(bool), typeof(ControlSettings),
              new PropertyMetadata(false));

    public static bool GetAccessIndirectProperty(DependencyObject d)
    {
        return (bool) d.GetValue(AccessIndirectPropertyProperty);
    }
    public static void SetAccessIndirectProperty(DependencyObject d, bool value)
    {
        d.SetValue(AccessIndirectPropertyProperty, value);
    }
}

然后,

<local:MyControl x:Name="myControl" 
                 AccessDirectProperty="True" 
                 ControlSettings.AccessIndirectProperty="True" />

将设置一个可以通过访问的值

var p = ControlSettings.GetAccessIndirectProperty(myControl); // yields True
© www.soinside.com 2019 - 2024. All rights reserved.