讓我們舉個例子。 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();
}
}
- 如何連接這些引用?
- 在我看來,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());
}
啊,沒錯。所以這是一個致命的例子。在指定位置(xaml中定義的位置)顯示哪些控件? – MistyK
然後你應該使用WebBrowser控件:http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff431797(v=vs.105).aspx – anderZubi
我不同意這個答案,因爲直接調用這個任務你刪除了嘲弄的支持。 –