簡體   English   中英

WPF調用方法與屬性

[英]WPF call method with property

我對WPF不太熟練。 我想要做的是從我的視圖綁定到屬性,然后用某些東西設置該值。 我已經沒有遇到麻煩,但我覺得我沒有正確使用MVVM模式。 我在ViewModel中擁有我的屬性,綁定到View但是我似乎無法使Model部分工作,因為我打算將屬性從其獲取其值的方法當前也在ViewModel中。

這是我現在擁有的:

public class MainViewModel : ViewModelBase
{
    private Awesome _model; //this is my model
    private string _score;

    public string Score
    {
        get { return GetScore(); }
        set
        {
            _score = value;
        }
    }

    public string GetScore()
    {
        try
        {
            using (StreamReader sr = new StreamReader(@"C:\somepath"))
            {
                String line = sr.ReadToEnd();
                return line;
            }
        }
        catch (Exception)
        {
            MessageBox.Show("File could not be found! :(");
            throw;
        }
    }
}

這很好,但現在一切都在ViewModel中。 據我所知,GetScore()應該在Model中,但是我不知道如何用它來設置屬性。 我在這里錯過了什么?

GetScore() - GetScore()不應該在模型中。 模型是數據層,因此只有具有屬性的數據對象。 方法和其他東西由ViewModel協調。 因此,您可以在ViewModel中放置GetScore-Method,或將其移至另一個類並從ViewModel中調用它。

順便說一句:你的財產有點奇怪。 因為你的二傳手你正在設置一個永遠不會再使用的后端區域。 你確定這是你想要的嗎? 您也不應該總是在getter中讀取文件。

也許你想做的事情如下:

public string Score
{
    get { return _score ?? (_score = GetScore()); }
}

因此,您只需讀取一次文件並將值保存在_score中。

您的GetScore()屬於ViewModel,因為它是數據層。 (當然你可以將它移動到另一個類,但它不是來自我在ViewModel中的POV的wrog,將它視為擴展的getter;))

  1. 您應該將GetScore設為私有,因為您有一個屬性
  2. 您不應該從ViewModel影響UI,因此我建議您不要從ViewModel打開MessageBox。
  3. 使用return this.GetScore()

暫無
暫無

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

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