gpt4 book ai didi

c# - MVVM 灯 : Pass object from view to viewmodel

转载 作者:太空宇宙 更新时间:2023-11-03 16:28:36 25 4
gpt4 key购买 nike

我最近开始使用 MVVM light 来处理 WPF,并且我有以下(简单场景)。

  1. MainWindow 包含一个元素列表框。

  2. When one is selected and the button is clicked, I fire a command:

    ReservoirViewerCommand.Execute(null);
  3. 在 viewmodel 类上,我实例化命令并使用所选对象发送消息:

    ReservoirViewerCommand = new RelayCommand(OpenReservoir);
    private void OpenReservoir()
    {
    Messenger.Default.Send(new LaunchShowReservoirMessage(){Reservoir=SelectedReservoir});
    }

    哪里:

    class LaunchShowReservoirMessage:MessageBase
    {
    public Reservoir Reservoir { get; set; }
    }
  4. 主视图注册消息并打开一个新的子窗口:

    private void RegisterMessages() 
    {
    Messenger.Default.Register<LaunchShowReservoirMessage>(this,OnLaunchShowReservoir);
    }

    public void OnLaunchShowReservoir(LaunchShowReservoirMessage msg) {
    var showReservoir = new ReservoirViewerView();
    showReservoir.Show();
    }

我需要的是新的 ViewModel (ReservoirViewerViewModel) 可以通过消息以某种方式获取传递的对象,以便我可以在子窗口上显示该对象的详细信息。

我进行了一些逐步调试,但似乎永远无法访问 ViewModel 构造函数。

最佳答案

"I did some step-by-step debugging and the ViewModel constructor seems never to be reached."

确保您实际使用以下方法之一将您的 View 绑定(bind)到您的 View 模型:

代码隐藏

var showReservoir = new ReservoirViewerView();
showReservoir.DataContext = ViewModelLocator.ReservoirViewerViewModel; //static property
//OR showReservoir.DataContext = new ReservoirViewerViewModel();
showReservoir.Show();

Xaml View 中

<Window x:Class="Garmin.Cartography.AdminBucketTools.ChildWindowView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding Path=ReservoirViewerViewModel, Source={StaticResource Locator}}">
<!--Use the non-static property in your ViewModelLocator-->

<Grid />
</Window>

Xaml 资源

<DataTemplate DataType="{x:Type viewmodels:ReservoirViewerViewModel}">
<views:ReservoirViewerView/>
</DataTemplate>

"What I need is that the new ViewModel (ReservoirViewerViewModel) can somehow get hold of the passed object through the message so that I can then display the details of this object on the child window."

只需在您的 ReservoirViewerViewModel 类中注册相同的消息:

Messenger.Default.Register<LaunchShowReservoirMessage>(this, (msg) =>
{
var reservoir = msg.Reservoir;
});

仅供引用,如果您从 GenericMessage<[content type]> 而不是 MessageBase 派生消息类,则可以使用 GenericMessage 类的已定义内容属性。例如:

public class LaunchShowReservoirMessage: GenericMessage<Reservoir>
{
public LaunchShowReservoirMessage(Reservoir content) : base(content) { }
}

然后:

Messenger.Default.Register<LaunchShowReservoirMessage>(this, (msg) =>
{
var reservoir = msg.Content;
});

关于c# - MVVM 灯 : Pass object from view to viewmodel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11628908/

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