【发布时间】:2017-07-10 12:01:58
【问题描述】:
我必须在我的主 ViewModel 中启动某种子窗口,用户将在这个子窗口上输入一些文本,我必须在关闭子窗口后在主视图模型中使用这些文本。
我可以弹出一个子窗口,我绑定到它的子窗口视图模型
我启动子窗口的主视图模型是:
private void OpenLayoutNameWindow()
{
LayOutName_VM chldWindow =new LayOutName_VM();
chldWindow.Show();
string layOutName = chldWindow.LayOutName;
MessageBox.Show("Name is:"+ layOutName); //this message box is popuped before i close the child window save button and its empty.
}
这是子窗口的视图:
<StackPanel>
<Label Margin="0,5,0,0" HorizontalAlignment="Center">Please name your new Layout</Label>
<TextBox Margin="0,5,0,0" Width="120" Height="20" HorizontalAlignment="Center" Text="{Binding LayOutName, Mode=TwoWay}"></TextBox>
<Button Margin="0,5,0,0" Width="80" Height="20" HorizontalAlignment="Center" Command="{Binding CloseWindowCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}"> Save</Button>
</StackPanel>
这是后面的代码:
public partial class LayOutName : Window
{
public LayOutName()
{
InitializeComponent();
this.DataContext = new LayOutName_VM(); ;
}
}
这是子窗口视图模型:
class LayOutName_VM : ViewModelBase
{
public ActionCommand<Window> CloseWindowCommand { get; private set; }
public LayOutName_VM()
{
this.CloseWindowCommand = new ActionCommand<Window>(this.SaveLayOutName);
}
private string layOutName;
public string LayOutName
{
get
{
return layOutName;
}
set
{
layOutName = value;
RaisePropertyChanged("LayOutName");
}
}
private void SaveLayOutName(Window wind)
{
wind.Close();
}
internal void Show()
{
LayOutName ly = new BrukerApp.LayOutName();
ly.Show();
}
}
如何将子窗口中输入的文本获取到视图模型类。
【问题讨论】:
-
如果您尝试使用 MVVM,您的代码中不应包含任何内容。我看到你有一个
ViewModelBase,你在使用其中一个 MVVM 库吗?如果是这样,我会调查你的Mediator模式或EventAggregator模式的风味实现。
标签: c# .net wpf mvvm childwindow