【问题标题】:XAML setting property of property属性的 XAML 设置属性
【发布时间】:2021-03-19 12:36:47
【问题描述】:

在 XAML 中,有没有办法设置属性的属性?

这里有一个例子来说明:

public class SomeControl : Control
{
    public SomeType SomeProperty { get; } = new SomeType(); // Property deliberately read only 
}

public class SomeType
{
    public string Name { get; set; }
}

在下面的 XAML 中,我想设置 «SomeProperty» 属性的 «Name» 值,而不向 «SomeProperty» 添加设置器,因此不创建 «SomeType» 的新 XAML 实例。

<ns:SomeControl SomeProperty.Name ="Foo"> <!-- here is the idea, but does not compile  -->
</ns:SomeControl>

问候

【问题讨论】:

  • 不可能...这样的语法适用于附加属性
  • 我知道附加属性的这种语法,但是没有其他语法可以满足这种需要吗?
  • 有什么好的理由让这不可能吗?
  • 我不知道?也许这样的语法是针对附加属性的事实,它搜索 SomePropertySomeProperty.Name="Foo" 类型的父级就像 SomeProperty.SetName(control, "Foo")

标签: c# .net xaml


【解决方案1】:

如果您使 SomeControl.SomeProperty 可设置,那么您可以通过 XAML 设置名称

public class SomeControl : Control
{
    public SomeType SomeProperty { get; set; }
}

public class SomeType
{
    public string Name { get; set; }
}

XAML 可能是..

<Window ...>
    <Window.Resources>
        <ns:SomeType x:Key="someType" Name="Hello World"/>
    </Window.Resources>
    
    <Grid>
        <ns:SomeControl SomeProperty="{StaticResource someType}"/>
    </Grid>
</Window>

【讨论】:

  • 我知道,如果我让 SomeProperty 可设置,那么我可以设置 Name 属性,但是在此可以使用 XAML 创建 SomeControl 的新实例,而这正是我想要避免的。 . 这就是为什么我写了«属性故意只读»
  • 嗯...您说“我们使用 XAML 创建 SomeControl 的新实例,而这正是我想要避免的...”但 &lt;ns:SomeControl .../&gt; 是对象创建。如果没有在 XAML 中创建对象,您将无法访问它
【解决方案2】:

你的属性是只读的

如果它没有设置属性,则无法设置它

你甚至在写:// Property deliberately read only

那么你需要设置它还是只读的?

【讨论】:

  • 我正在尝试设置读/写的 Name 属性的值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多