我创建了一个视图(MyView),其中包含了一个像这样的UserControl:
<StackPanel>
<ctrl:ViewDialog DataContext="{Binding CtrlViewDialog}" Message="Hello" Name="ctrlViewDialog" >
</ctrl:ViewDialog>
视图背后的代码:
public MyView()
{
InitializeComponent();
var _message = ctrlViewDialog.Message;
}
[Dependency]
public MyViewViewModel ViewModel
{
get
{
return (MyViewViewModel)this.DataContext;
}
set
{
this.DataContext = value;
}
}
并且视图模型MyViewViewModel是:
public MyViewViewModel()
{
ViewDialogViewModel CtrlViewDialog = new ViewDialogViewModel(Message);
}
包含的UserControl(ViewDialog)背后的代码是:
private string message;
public string Message
{
get { return message; }
set { message = value; }
}
public ViewDialog()
{
InitializeComponent();
}
如何将MyView的"_message"
参数传递给MyViewViewModel,以便将其传递给实例ViewDialogViewModel CtrlViewDialog = new ViewDialogViewModel(Message);
答案 0 :(得分:2)
好的我会尝试回答您实际问过的树问题。 首先是与c#有关。你能做到吗?
public MyViewViewModel()
{
ViewDialogViewModel CtrlViewDialog = new ViewDialogViewModel(Message);
}
在填充属性之前,不会始终运行构造函数。
其次,您可以使用WPF将此值传递给视图模型吗? 是。它也可以在构造函数中完成,但这需要更多的代码。当控件加载更容易时,你可以做到这一点。
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:vm="clr-namespace:PrismTest.ViewModels"
xmlns:view="clr-namespace:PrismTest.Views"
x:Class="PrismTest.Views.TestView"
prism:ViewModelLocator.AutoWireViewModel="True">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding LoadedCommand}" CommandParameter="{Binding Message, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type view:TestView}}}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<Grid>
<StackPanel>
<TextBlock Text="{Binding Message, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type view:TestView}}}"/>
<TextBlock Text="{Binding Message}"/>
</StackPanel>
</Grid>
</UserControl>
命令
private ICommand loadedCommand = new DelegateCommand<string>(text =>
{
MessageBox.Show(text);
});
public ICommand LoadedCommand { get { return loadedCommand; } }
现在你应该在棱镜中做些什么?传递参数是好的。执行此ViewDialogViewModel CtrlViewDialog = new ViewDialogViewModel(Message);
和此
(MyViewViewModel)this.DataContext;