C# MVVM-按钮命令绑定不工作
我正在使用MVVM模式开发WPF应用程序。 然而,由于这是我第一次尝试使用MVVM模式,所以我在使用它时遇到了麻烦 我有一个主窗口视图和两个用户控件,我想用按钮来切换。虽然很简单,但我还是被以下代码卡住了,这些代码应该可以工作,但当我点击按钮时什么也并没有发生: MainView.xamlC# MVVM-按钮命令绑定不工作,c#,wpf,mvvm,binding,C#,Wpf,Mvvm,Binding,我正在使用MVVM模式开发WPF应用程序。 然而,由于这是我第一次尝试使用MVVM模式,所以我在使用它时遇到了麻烦 我有一个主窗口视图和两个用户控件,我想用按钮来切换。虽然很简单,但我还是被以下代码卡住了,这些代码应该可以工作,但当我点击按钮时什么也并没有发生: MainView.xaml <Window x:Class="WindowsClient.View.MainView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml
<Window x:Class="WindowsClient.View.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:WindowsClient.ViewModel"
xmlns:local="clr-namespace:WindowsClient.View"
Height="768" Width="1366" MinHeight="768" MinWidth="1366">
<Window.Resources>
<DataTemplate DataType="{x:Type vm:HomeViewModel}">
<local:HomeView/>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:ProfilViewModel}">
<local:ProfilView/>
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="240"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<!-- LeftMenu -->
<Border Grid.Column="0" Background="Black">
<StackPanel>
<Button Content="Home" Command="{Binding HomeViewCommand}"></Button>
<Button Content="Profil" Command="{Binding ProfilViewCommand}"></Button>
</StackPanel>
</Border>
<!-- Body -->
<ContentControl x:Name="Pages" Content="{Binding ContentControlViewModel}" Grid.Column="1"/>
</Grid>
ProfilView和ProfilViewModel与这两个基本相同
无论如何,当我单击一个按钮时,视图没有改变,我不明白为什么…MainView中缺少此位。xaml:
<Window.DataContext>
<local:MainWindowViewModel/>
</Window.DataContext>
您可以将其添加到
行的正上方
这就是为什么没有任何东西从viewmodel绑定到您的视图。我假设您正在单击“主页”或“Profil”按钮,对吗?您是否尝试过在
OpenHome
或OpenProfil
中设置断点以查看您的命令是否正在执行?MainView
上的DataContext
是否实际设置为MainWindowViewModel
实例?是的。我在OpenHome/OpenProfil
中尝试了断点,但它似乎从未到达。我将四处寻找DataContext,也许我遗漏了一些东西。这就是问题所在。非常感谢。
<UserControl x:Class="WindowsClient.View.HomeView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Height="768" Width="1126"
MinHeight="768" MinWidth="1126">
<Grid>
<ToggleButton x:Name="CommunityButton" Content="Community" Height="30" Width="200" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="-300,100,0,0" FontSize="18" />
<ToggleButton x:Name="NewsButton" Content="News" Height="30" Width="200" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="300,100,0,0" FontSize="18"/>
<ScrollViewer x:Name="HomeContentViewer" Margin="10,150,10,10"/>
</Grid>
</UserControl>
namespace WindowsClient.ViewModel
{
internal class HomeViewModel
{
}
}
<Window.DataContext>
<local:MainWindowViewModel/>
</Window.DataContext>