gpt4 book ai didi

c# - MVVM C#​​ 在 View (窗口)之间传递数据

转载 作者:行者123 更新时间:2023-11-30 14:50:17 24 4
gpt4 key购买 nike

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();
}
}

命令类.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>

我用谷歌搜索并找到了一个项目,但它太复杂了,请建议我的 2) 问题的答案会有所帮助。谢谢。

最佳答案

这就是我要做的。在调用按钮的命令中,我会这样做:

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

编辑

看到你的代码,你可以这样做,因为我认为两个窗口共享 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/

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