Tôi đang tạo ứng dụng Windows Phone 7 và tôi cần tham chiếu đến ViewModel trong chế độ xem của mình để tôi có thể đặt thuộc tính từ trình xử lý sự kiện của mình. Vấn đề duy nhất là tôi không thể lấy tham chiếu đó.MVVMLight - cách nhận tham chiếu đến ViewModel trong Chế độ xem?
Điều tôi đã làm;
Tôi có một ViewModelLocator (xóa các bit không liên quan):
static ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<TunerViewModel>();
}
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This non-static member is needed for data binding purposes.")]
public TunerViewModel Tuner
{
get { return ServiceLocator.Current.GetInstance<TunerViewModel>(); }
}
Và một cái nhìn (XAML):
DataContext="{Binding Tuner, Source={StaticResource Locator}}">
Và code-behind của quan điểm:
public partial class Tuner : PhoneApplicationPage
{
private readonly TunerViewModel _viewModel;
public Tuner()
{
_viewModel = DataContext as TunerViewModel;
InitializeComponent();
}
Tôi tìm thấy liên kết này MVVM View reference to ViewModel nơi DataContext được truyền tới ViewModel, vì vậy tôi đã thử cùng một b ecause nó trông giống như một giải pháp tốt. Tuy nhiên, trường _viewModel của tôi là null sau khi cast. Tại sao điều này và làm thế nào để tôi sửa lỗi này? Tôi không thể tìm thấy nó trên Google/Stackoverflow
Cảm ơn trước :)
Cậu lập Locator tài nguyên App.xaml của bạn (hoặc cách khác, nhưng không phải là khô, tài nguyên trang của bạn)? Bởi vì điều này có vẻ như nó không phải là tìm kiếm mô hình viewModel trong ràng buộc XAML của bạn. – Robaticus