[英]Wpf Prism - Passing parameter from view to viewmodel
我創建了一個視圖(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);
好的,我會嘗試回答您實際問過的樹問題。 首先是與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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.