gpt4 book ai didi

wpf - 在 MVVM 中实现命令

转载 作者:行者123 更新时间:2023-12-04 06:55:36 25 4
gpt4 key购买 nike

我正在尝试在执行 SampleCommand 时更改 Page1.xaml 中框架的源属性。
我如何在 View 模型中实现这一点?

第1.xaml:

<Page ...>
<DockPanel>
<r:ribbon>
<r:RibbonTab Label="Keys">
<r:RibbonTab.Groups>
<r:RibbonGroup GroupSizeDefinitions="{StaticResource RibbonLayout}">
<r:RibbonGroup.Command>
<r:RibbonCommand LabelTitle="RibbonButton"/>
</r:RibbonGroup.Command>
<r:RibbonButton x:Name="RibbonButton1" Command="{Binding Path=SampleCommand}"/>
</r:RibbonGroup>
</r:RibbonTab.Groups>
</r:RibbonTab>
</r:Ribbon>

<Border Name="PageBorder" Grid.Row="0" Grid.Column="1">
<Frame Name="pageFrame" Source="FirstPage.xaml" />

</Border>
</DockPanel>
</Page>

Page1ViewModel.cs:
RelayCommand _sampleCommand;

public ICommand SampleCommand
{
get
{
// create command ??

return _sampleCommand
}
}

page1.xaml.cs:
Page1ViewModel pageViewModel;

//When page loads

this.DataContext = pageViewModel;

最佳答案

根据您使用的 RelayCommand 的实现,它应该将 Action 作为其构造函数的参数,该构造函数表示在实现时要调用的代码。所以在你的 ViewModel 中:

_sampleComand = new RelayCommand(() => DoStuff());

但是,这里的问题是您想在 ViewModel 无法访问的“pageFrame”控件上调用 Navigate。

解决这个问题的最简单方法可能是将 Frame 的 NavigationService 作为参数传递给命令。您可能需要更改 _sampleCommand 的声明,以便它知道它需要一个参数; RelayCommand 的一些实现还定义了一个 RelayCommand<T>这是一个接受强类型参数的命令。
private ICommand _sampleCommand;
...
_sampleCommand = new RelayCommand<NavigationService>(
ns => ns.Navigate(destinationUri));

所以现在你需要将框架的 NavigationService 传递给命令:
<r:RibbonButton x:Name="RibbonButton1" 
Command="{Binding Path=SampleCommand}"
CommandParameter="{Binding NavigationService,ElementName=pageFrame}"
/>

由于您的 ViewModel 可能会有一大堆导航命令,因此在 ViewModel 本身上设置 NavigationService 类型的属性并在您初始化事物时让页面将其连接到其框架可能更容易。这样您就可以引用该属性,而不是每次都将其作为命令参数传入。

关于wpf - 在 MVVM 中实现命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2604645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com