Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# WPF应用程序中未正确执行命令绑定_C#_Wpf_Data Binding - Fatal编程技术网

C# WPF应用程序中未正确执行命令绑定

C# WPF应用程序中未正确执行命令绑定,c#,wpf,data-binding,C#,Wpf,Data Binding,我想在我的WPF应用程序中实现我的导航。目前StartScreen.xaml在启动时显示,但当我单击按钮时,DeviceManagement.xaml未显示。甚至没有调用ShowDeviceManagement命令 <UserControl ...> <Button Content="Click Me" Command="{Binding DataContext.ShowDeviceManagement, RelativeSourc

我想在我的WPF应用程序中实现我的导航。目前StartScreen.xaml在启动时显示,但当我单击按钮时,DeviceManagement.xaml未显示。甚至没有调用ShowDeviceManagement命令

<UserControl ...>
     <Button
         Content="Click Me"
         Command="{Binding DataContext.ShowDeviceManagement, RelativeSource={RelativeSource AncestorType={x:Type vm:MainWindowViewModel}}, Mode=OneWay}"/>
</UserControl>
这让我假设按钮的命令不正确?我怎样才能修好它

<UserControl ...>
     <Button
         Content="Click Me"
         Command="{Binding DataContext.ShowDeviceManagement, RelativeSource={RelativeSource AncestorType={x:Type vm:MainWindowViewModel}}, Mode=OneWay}"/>
</UserControl>
App.xaml

<Application.Resources>
    <DataTemplate DataType="{x:Type vm:DeviceManagementViewModel}">
        <view:DeviceManagement />
    </DataTemplate>

    <DataTemplate DataType="{x:Type vm:MainWindowViewModel}">
        <view:StartScreen />
    </DataTemplate>
</Application.Resources>
<UserControl ...>
     <Button
         Content="Click Me"
         Command="{Binding DataContext.ShowDeviceManagement, RelativeSource={RelativeSource AncestorType={x:Type vm:MainWindowViewModel}}, Mode=OneWay}"/>
</UserControl>
“DataContext”在命令绑定中已过时。RelativeSource用于在可视树中查找祖先,而您的MainWindowViewModel不可视。应该是这样的:

<UserControl ...>
     <Button
         Content="Click Me"
         Command="{Binding DataContext.ShowDeviceManagement, RelativeSource={RelativeSource AncestorType={x:Type vm:MainWindowViewModel}}, Mode=OneWay}"/>
</UserControl>
Command="{Binding ShowDeviceManagement, Mode=OneWay}"

尝试初始化RelayCommand并在构造函数中将其设置为private字段,在ShowDeviceManagement属性中只返回此字段,而不是在每次访问属性时创建命令实例。