2014-02-10 57 views
0

讓我們舉個例子。 WebBrowserTask類提供我們在控件中打開指定的URL。我們在我們看來定義它。如何在viewmodel中獲得對該控件的引用?我們應該在視圖中創建它,並在代碼後面使用「webBrowserTaskInstance.Show()」嗎?或者是否有可能在MVVM模式中使用「Show()」函數?使用帶有MVVM WP8功能的控件c#/ xaml

編輯:WebBrowserTask的例子是錯誤的。讓我們再舉一個例子:

 public class MainViewModel 
     { 
       private IInternetService _internetService; 

        public MainViewModel(IInternetService internetService) 
        { 
        _internetService = internetService; 
        } 

       RelayCommand ComputeCommand 
       { 
       get 
       { 
        blablabla -> _internetService.Compute(); 
       } 
       } 

     } 
我MainView.xaml

現在:

<namespace:InternetControl x:Name="MyControl" /> 

假設InternetControl有一個函數計算()和單文本框。在調用Compute()之後,它從互聯網獲取東西並寫入該文本框。

我希望我的ComputeCommand到(在這裏IInternetService)調用指定的服務,它實現纏上了我的控制,並在其上調用計算 - 例如:

public class InternetService : IInternetService 
{ 
     InternetControl internetControl; // how to spare reference to it with my control in view? 

    public void Compute() 
    { 
    internetControl.Compute(); 
    } 
} 
  1. 如何連接這些引用?
  2. 在我看來,InternetService類應該包含從互聯網上下載東西的邏輯,並且應該把它寫入自定義控件中,我是對嗎?

編輯2 - 這是解決方案,但在我看來,控制應該是ViewModel獨立的,我是對嗎? 視圖模型:

public ICommand ResetCommand {get; set;} 

從用戶控件的OnLoad方法:

private void MyUserControl_Loaded(object sender, RoutedEventArgs e) 
{ 
    MyUserControl ctrl = sender as MyUserControl; 
    if (ctrl == null) return; 

    MyViewModel vm = ctrl.DataContext as MyViewModel ; 

    if (vm == null) 
     return; 

    vm.ResetCommand = new RelayCommand(param => this.Reset()); 
} 

回答

1

WebBrwoserTask類沒有在你的應用程序中定義的Web控件打開一個指定的URL。它會在手機的本地網絡瀏覽器應用程序中打開它。

您可以從您的視圖模型啓動任務:

WebBrowserTask task = new WebBrowserTask(); 
task.Uri = new Uri("http://your-url-here"); 
task.Show(); 
+0

啊,沒錯。所以這是一個致命的例子。在指定位置(xaml中定義的位置)顯示哪些控件? – MistyK

+0

然後你應該使用WebBrowser控件:http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff431797(v=vs.105).aspx – anderZubi

+0

我不同意這個答案,因爲直接調用這個任務你刪除了嘲弄的支持。 –

0

我沒有正確地得到您的問題,但可能是你想顯示從視圖模型的東西嗎? 你可以做一件事情通過返回值在View Model中創建一個標誌,並在View中對其進行訪問。

0

這取決於您使用的框架。您可以使用委託,服務或消息來抽離任務。你不應該把它放在視圖中,也不應該直接從視圖模型中調用它,因爲這是不可嘲弄的。