2016-10-06 41 views
0

我是一個做小WPF MVVM程序:鏈接ViewModel類查看

  1. 具有與標籤一個主窗口(說「你好」)和一個按鈕打開另一個窗口(我沒有打開的窗口部分在後面的代碼中)。
  2. 這會打開另一個帶有2個單選按鈕(紅色和藍色)和一個取消按鈕(我在後面的代碼中關閉了功能)的窗口。
  3. 如果按下紅色單選按鈕,MainWindow上的標籤應該變成紅色,同樣按下藍色單選按鈕。

有人可以幫助我嗎?我對WPF很陌生,對MVVM方法學來說也是全新的。我張貼我的ViewModel代碼:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Input; 
using System.Windows.Media; 
using PocMVVM.Views; 


namespace PocMVVM.ViewModel 

{ 

    public class ColorChangeViewModel : ICommand 

    { 

     //ColorChoiceView colorSelect = new ColorChoiceView(); 
     //MainWindow mw = new MainWindow(); 
     public event EventHandler CanExecuteChanged; 

     public bool CanExecute(object parameter) 
     { 
      return true; 
      //throw new NotImplementedException(); 
     } 

     public void Execute(object parameter) 
     { 
      //throw new NotImplementedException(); 
      ColorChoiceView colorSelect = new ColorChoiceView(); 
      MainWindow mw = new MainWindow();  
      if((bool)parameter==colorSelect.RedButton.IsChecked.Equals(true)) 
      { 
       mw.label.Foreground = Brushes.Red; 
       mw.UpdateLayout(); 
       mw.ShowDialog(); 
      } 
      else if((bool)parameter == colorSelect.BlueButton.IsChecked.Equals(true)) 
      { 
       mw.label.Foreground = Brushes.Blue; 
       mw.UpdateLayout(); 
       mw.ShowDialog(); 
      } 
     } 
    } 
} 

有人可以幫我嗎?

非常感謝!

P.S.我知道人們可能會問是否需要兩個窗口,但必須這樣。我被告知它必須是這樣的,所以別無他法。

+0

我在哪裏查看代碼?你爲什麼在ViewModel中引用你的MainWindow? –

+0

這不是唯一訪問標籤的方法嗎? –

+0

不,它不是訪問的方式。如果你正在使用MVVM使用數據綁定,命令等。我建議你在編寫代碼之前閱讀更多關於MVVM模式和WPF的信息 –

回答

0

首先,您不應該在視圖模型中引用視圖。根據MVVM模式,您應該將視圖的DataContext設置爲您的視圖模型,但視圖模型不應該對視圖一無所知。 如果你想讓你的命令打開一個窗口,你可以使用服務。看看這個:Opening new window in MVVM WPF

此外,你可以綁定到前景色。在您的視圖模型,你應該有這樣的事情:

public System.Windows.Media.Brush ForegroundColor 
{ 
    get { return _foregroundColor; } 
    set 
    { 
     _foregroundColor = value; 
     OnPropertyChanged("ForegroundColor"); 
    } 
} 

而且與你好標籤XAML:

<TextBlock Foreground="{Binding Path=ForegroundColor, Mode=TwoWay}" /> 

而且單選按鈕,你應該有一個ICommand當你們之間的切換響應兩種顏色,並進一步將您的屬性ForegroundColor設置爲此值。像這樣(在XAML):

<RadioButton Content="Red" Command="{Binding SwitchButtonCommand}" CommandParameter="Red" /> 
<RadioButton Content="Blue" Command="{Binding SwitchButtonCommand}" CommandParameter="Blue" /> 

而在SwitchButtonCommand命令你可以設置ForegroundColor爲紅色或藍色,根據參數的實施。

+0

但是,這是如何鏈接到單選按鈕的?主要目標是使用單選按鈕更改標籤顏色? –

+0

什麼是OnPropertyChanged()?我如何實現它? –

+0

我已經編輯了我的答案,但是我建議你首先閱讀綁定,INotifyPropertyChanged等的介紹,否則使用MVVM沒有意義。看看這裏例如:http://www.learnmvvm.com/ – Michelle