1)在多个 View 之间传递数据的最佳方法是什么?

2)我有方案(MVVM C#):

MainWindow中的TextBox和Button和Window1中的TextBlock
在按钮上单击(我正在使用Icommand),MainWindow的TextBox中的数据必须出现在Window1的TextBlock中吗?

ViewModelBase.cs

public class ViewModelBase
{
    public Commandclass commandclass { get; set; }

    public ViewModelBase()
    {
        commandclass = new Commandclass(this);
    }

    private string fname;
    public string vmname
    {
        get { return fname; }
        set { fname = value; }
    }

    public void OnCommand()
    {
        Window1 w = new Window1();
        /* How to bind ???*/
        w.Show();
    }
}

CommandClass.cs
public class Commandclass : ICommand
    {
        public ViewModelBase vmclass { get; set; }
        public Commandclass(ViewModelBase vmb)
        {
            vmclass = vmb;
        }

        public bool CanExecute(object parameter)
        {
            return true;
        }
        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            vmclass.OnCommand();
        }
    }

观看次数
**MainWindow.xaml**

<Window x:Class="Multiwindow.MainWindow"
        …
        xmlns:vm="clr-namespace:Multiwindow.Viewmodel">
    <Window.Resources>
        <vm:ViewModelBase x:Key="vmodel"/>
    </Window.Resources>

    <Grid Background="Gray" DataContext="{StaticResource vmodel}">

        <TextBox Height="26" Margin="194,115,154,179" Width="169"
                  Text="{Binding vmname, Mode=TwoWay}"/>
        <Button Content="Button1" HorizontalAlignment="Left"
                Margin="251,158,0,0" VerticalAlignment="Top"
                Command="{Binding commandclass, Source={StaticResource vmodel}}"/>

    </Grid>
</Window>

**Window1.xaml**

<Window.Resources>
        <vm:ViewModelBase x:Key="vmodel"/>
</Window.Resources>
<Grid >
    <TextBlock FontSize="20" Height="28" Width="169" Foreground="Black"
                    Background="Bisque" />
</Grid>

我已经在Google上搜索并找到了一个项目,但是它很复杂,请提出我的2)问题的答案将对您有所帮助。

最佳答案

这就是我要做的。在按钮上调用的命令中,单击“我将执行以下操作”:

Window2 w= new Window2();
w.DataContext=new Window2ViewModel();
((Window2ViewModel)w.DataContext).TextForTextblock=TextFromTextbox;
w.Show();

编辑

看到您的代码,您可以执行此操作,因为我认为两个Windows都共享ViewModelBase:
Window1 w= new Window1();
w.DataContext=this;
w.Show();

您还必须绑定(bind)TextBlock:
<TextBlock FontSize="20" Height="28" Width="169" Foreground="Black"
                Background="Bisque" Text="{Binding vmname}"/>

关于c# - MVVM C#在 View 之间传递数据(窗口),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37046584/

10-17 02:07
查看更多