簡體   English   中英

從 XAML 訪問間接屬性 - WPF

[英]Access Indirect property from XAML - WPF

我有一個名為MyControl的 Control 類,它具有直接布爾屬性AccessDirectProperty和一個對象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 訪問直接屬性AccessDirectProperty ,而不會出現任何錯誤。

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

但是我無法從 XAML 中的對象ControlSettings訪問屬性AccessIndirectProperty 下面的代碼無法做到這一點。

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

誰可以幫我這個事?

恐怕 XAML 不支持訪問“嵌套”屬性。

但是,您可以使ControlSettings成為具有附加屬性的獨立類:

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

現在,在技術層面上,以下內容對於修改通過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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM