我当然希望这个问题易于回答,但是已经过去了几天,我还没有弄清楚如何在UserControls之间共享数据。
下面的页面有两个选项卡,并引用了它们的来源。它还具有一个标记为Start的按钮,用于访问ViewModel中的命令。
我遇到的问题是数据实际上在选项卡中。我将它们设置为使用相同的ViewModel,并且它们各自创建自己的ViewModel实例,因此数据永远不会显示在“开始”按钮上。我希望从那以后。
这是一个相当简单的程序,我真的没有看到需要仅包含单个元素的3个独立ViewModel的必要,但也许这就是我需要做的。总而言之,当我点击开始按钮时,我仍然需要从所有内容中收集所有数据并将其提交给外部实体。
如果这是之前提出的问题,我深表歉意,但是我对C#比较陌生,所以我不确定自己要问什么。提前致谢!
<UserControl
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"
xmlns:mui="http://firstfloorsoftware.com/ModernUI"
x:Class="DeployWiz.Pages.Config"
mc:Ignorable="d"
xmlns:local="clr-namespace:DeployWiz.ViewModel"
d:DesignHeight="356.978" d:DesignWidth="333.582">
<Grid Style="{StaticResource ContentRoot}" Margin="16,28,16,5" >
<Grid.DataContext>
<local:ComputerViewModel/>
</Grid.DataContext>
<mui:ModernTab x:Name="tabList" Layout="List" SelectedSource="/Views/ComputerView.xaml" Margin="0,0,0,40">
<mui:ModernTab.Links>
<mui:Link DisplayName="Settings" Source="/Views/ComputerView.xaml" />
<mui:Link DisplayName="Applications" Source="/Views/ApplicationView.xaml" />
</mui:ModernTab.Links>
</mui:ModernTab>
<Button Content="Start" HorizontalAlignment="Center" Margin="0,0,0,5" VerticalAlignment="Bottom" Width="75" Command="{Binding Path=StartTask}"/>
</Grid>
</UserControl>
您是否使用任何MVVM框架?
这取决于不同的方法,通常是多个视图访问一个视图模型。
一个,如果已经实例化
this.DataContext = ViewModelName(); (c的后端代码中的数据上下文绑定)
我相信MVVM Light工具包将在ViewModel Locator中为您执行此操作
Also u can read this posts answer to make static viewmodels in the App.xaml.cs file singleton One ViewModel and multiple views
I think you need to be consistent. If you decided to distribute responsibility of handling data in each View/UserControl to different ViewModels then the same way need to be applied when passing the data to outside entity. Each ViewModels responsible to pass the data. Having a button outside those controls is not an issue. There is Mediator Pattern as a best practice to communicate between viewmodels. That way you can send message to ViewModels in each control from the button's viewmodel. Upon receiving the message from button, you can instruct them to pass the data to outside entity.
"communication between viewmodels wpf" is the keyword to search for your problem here. If you use MVVM Light, sending message and subscribing to a message is as simple as shown here. Other major MVVM framework like Calliburn and Prism also has it. Otherwise you can search for simple implementation of Mediator pattern (I guess many people has implemented it, you can use their codes).
根据我的理解,我会像这样实现它-
MainWindowViewModel-
主窗口-
ComputerViewModel-
这种方法的好处-
让我知道您是否有任何疑问或不清楚的地方。