【问题标题】:How to bind a property of inherited class from abstract class如何从抽象类绑定继承类的属性
【发布时间】:2019-10-16 21:54:41
【问题描述】:

我有一个带有一些继承类的抽象类:

public abstract class Base
{    
    public Base()
    {
    }
}

public class InheritedA : Base
{
    public bool PropertyA { get; set; }

    public InheritedA()
    {
    }
}

public class InheritedB : Base
{
    public bool PropertyB { get; set; }

    public InheritedB()
    {
    }
}

当我在 datacontext 类中只引用了一个“Base”类时,如何在 XAML 中绑定继承类的 PropertyA:

public class DataContextHere: INotifyPropertyChanged
{
    public Base baseClass{ get; set; }
}

类似的东西?:

<RadioButton IsChecked="{Binding baseClass.PropertyA}">

编辑奖励: 并且,是否只有当布尔属性存在且为真时才可以绑定?

<RadioButton IsChecked="{Binding baseClass.PropertyA}">
<RadioButton IsChecked="{Binding baseClass.PropertyB}">

在这种情况下,如果在 baseClass 中引用了 InheritedA,则检查第一个单选按钮,如果引用了 InheritedA,则检查第二个单选按钮。

谢谢

【问题讨论】:

  • 您的 baseClass 字段必须是属性:public Base baseClass { get; set; }。您可能还需要实现 INotifyPropertyChanged。 baseClass 是什么属性?一个窗口,一个视图模型?请提供更多、更多、更多的细节。

标签: c# wpf inheritance data-binding


【解决方案1】:

和你一样,前提是baseClass 是一个公共属性,它实际上返回一个Inherited 实例:

<RadioButton IsChecked="{Binding baseClass.PropertyA}">

public Base baseClass { get; } = new Inherited();

【讨论】:

  • 这个。 WPF 使用动态反射来进行绑定。所以它不关心绑定了什么实例或什么类型。只要它具有预期名称的属性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-23
  • 1970-01-01
  • 2010-10-10
  • 2013-04-18
  • 2021-05-03
相关资源
最近更新 更多