Dot-Net
如何使用 DataContext 屬性在 XAML 中的視窗上設置 ViewModel?
這個問題幾乎說明了一切。
我有一個視窗,並嘗試使用 ViewModel 的完整命名空間設置 DataContext,但我似乎做錯了什麼。
<Window x:Class="BuildAssistantUI.BuildAssistantWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" DataContext="BuildAssistantUI.ViewModels.MainViewModel">
除了其他人提供的解決方案(很好且正確)之外,還有一種方法可以在 XAML 中指定 ViewModel,但仍將特定的 ViewModel 與 View 分開。當您想要編寫獨立的測試案例時,將它們分開很有用。
在 App.xaml 中:
<Application x:Class="BuildAssistantUI.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:BuildAssistantUI.ViewModels" StartupUri="MainWindow.xaml" > <Application.Resources> <local:MainViewModel x:Key="MainViewModel" /> </Application.Resources> </Application>在 MainWindow.xaml 中:
<Window x:Class="BuildAssistantUI.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" DataContext="{StaticResource MainViewModel}" />
試試這個。
<Window x:Class="BuildAssistantUI.BuildAssistantWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:VM="clr-namespace:BuildAssistantUI.ViewModels"> <Window.DataContext> <VM:MainViewModel /> </Window.DataContext> </Window>