【发布时间】:2020-07-30 20:10:47
【问题描述】:
我知道有很多类似的问题,我花了两个小时尝试实施它们,但无法继续。所以问题看起来很简单。当我没有视图模型时,我可以将数据上下文设置为一个类,并且使用该类传输数据非常容易。但是当有 viewmodel 时,我必须将 datacontext 设置为那个,然后找不到返回任何值的方法。我试图为这个问题实施无数的解决方案,但似乎它们超出了我的技能水平。非常感谢您的帮助!
我的代码的重要部分(它是一个我要保存的简单游戏,其中保存由用户输入命名)第一个窗口,我想从第二个窗口获取数据
case Key.Escape: {
Thread t = new Thread(() => {
SaveGameWindow pw = new SaveGameWindow(); //the second window
if ((pw.ShowDialog() == true) && (pw.Name != string.Empty)) //pw.Name always empty
{
ILogicSaveGame l = new LogicSaveGame();
l.Write(pw.Name, "saved_games.txt");
MessageBox.Show("game saved");
}
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
XAML(从现在开始一切都属于 SaveGameWindow):
<Window.Resources>
<local:SaveGameViewModel x:Key="my_viewmodel"/>
</Window.Resources>
<Grid DataContext="{StaticResource my_viewmodel}">
<TextBox Text="{Binding Name}"/> //i want to acces this in the first window
<Button Command="{Binding CloseCommand}"
Content="Save"/>
后面的代码:
private readonly SaveGameViewModel vm;
public SaveGameWindow()
{
this.InitializeComponent();
this.vm = this.FindResource("my_viewmodel") as SaveGameViewModel;
if (this.vm.CloseAction == null)
{
this.vm.CloseAction = new Action(() => this.Close());
}
}
视图模型
public class SaveGameViewModel : ViewModelBase
{
public SaveGameViewModel()
{
this.CloseCommand = new RelayCommand(() => this.Close());
}
public string Name { get; set; }
public ICommand CloseCommand { get; private set; }
public Action CloseAction { get; set; }
private void Close()
{
this.CloseAction();
}
}
我使用 galasoft mvvmlightlibs
【问题讨论】: