如何在不同对象中访问相同的属性?

时间:2012-08-31 10:03:05

标签: c# .net wpf oop mvvm

想象一下,我有这堂课:

Class Foo
{
    public Bar b1 { get; set; }
    public Bar b2 { get; set; }
    public Bar b3 { get; set; }

    public void UpdateBarsMyProp(bool value)
    {
        // ????
    }
}

Class Bar
{
    public bool MyProp { get; set; }

    public bool UpdateMyProp(bool value)
    {
        this.MyProp = value;
    }
}

在b1,b2和b3中更新属性MyProp的最佳方法是什么?

泛型?

代表?

修改

只是添加有关我的具体情况的更多信息:

我正在创建一个虚拟键盘,我正在使用WPF MVVM,所以我有:

KeyBoard ViewModel包含几个Key ViewModel,我无法将它们存储在List中,因为我的View(xaml文件)我需要将每个键信息绑定到特定的ViewModel。

现在,当用户按下虚拟移位按钮时,我需要我的Keyboard ViewModel对象来更新每个Key ViewModel中的显示字符。

4 个答案:

答案 0 :(得分:2)

您可以将属性放在List<Bar>(或者数组中,如果您愿意......)并迭代它。

所以:

public Bar b1 { get; set; }
public Bar b2 { get; set; }
public Bar b3 { get; set; }
// other Bar props...

private List<Bar> barsList = new List<Bar>(){ b1, b2, b3, ... };

public void UpdateBarsMyProp(bool value)
{
    foreach(Bar bar in barsList)
    {
        bar.MyProp = value;
    }
}

答案 1 :(得分:0)

也许你的例子很简单,但为什么不做呢

b1.MyProp = b2.MyProp = b3.MyProp = value;

另外,为什么还要使用UpdateMyProp方法呢?这与您拥有的属性setter方法相同。如果需要向setter添加更多逻辑,可以通过更改

来停止使用自动实现的属性
public bool MyProp { get; set; }

private bool myProp;

public bool MyProp
{
   get { return this.myProp; }
   set
   {
      // any logic here
      this.myProp = value;
   }
}

答案 2 :(得分:0)

如果所有bar对象都需要相同的MyProp,则可以将MyProp设置为static:

public static bool MyProp { get; set; }

然后,您可以使用以下内容编辑所有条形对象的所有MyProp:

Bar.MyProp = baz;

仅当所有Bar对象共享相同的MyProp

时才使用此选项

答案 3 :(得分:0)

你可能想要这样的事情。

class Foo
{
    private readonly IList<Bar> bars = new List<Bar>
        {
            new Bar(),
            new Bar(),
            new Bar()
        }

    public Bar this[int i]
    {
        get
        {
           return this.bars[i];
        }
    }

    public void UpdateBars(bool value)
    {
        foreach (var bar in this.bars)
        {
            bar.MyProp = value;
        }
    }
}

然后您可以像这样访问第一个栏

var foo = new Foo();
var firstBar = foo[0];

你可以bind to a indexer with a little convertor,这会让你的模型变得不那么脆弱。


如果您不想使用索引器,可以将设置器提升到Foo

Class Foo
{
    public Bar b1 { get; set; }
    public Bar b2 { get; set; }
    public Bar b3 { get; set; }

    public bool MyProp
    {
        set
        {
            if (this.b1 != null)
            {
                this.b1.MyProp = value;
            }

            if (this.b2 != null)
            {
                this.b2.MyProp = value;
            }

            if (this.b3 != null)
            {
                this.b3.MyProp = value;
            }
        }
    }
}