我在我的父ViewModel中有一个ObservableCollection,我想要在父视图中显示。所以我定义了一个子视图和一个子ViewModel处理按钮的点击。 如何从ObservableCollection中将每个项目放入相应的子ViewModel中,而不会丢失用于按钮单击处理的已设置的RelayCommands?WPF MVVM DataTemplate:从父视图模型注入模板ViewModel
代码隐藏我做的DataContext的是设置中选取适当的视图模型的唯一的事我父视图:
DataContext = new ParentViewModel();
在我父视图XAML我定义了一个列表框,以显示我的孩子查看一个DataTemplate:
<ListBox
ItemsSource="{Binding Path=Items}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type vm:ChildViewModel}">
<views:ChildView Width="auto" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
现在在我的ChildView我有几个的TextBlocks显示数据绑定和按钮应该在的ObservableCollection中指定的路径执行文件:
<TextBlock
Text="{Binding Path=Title}" />
...
<Button
Content="Start exe"
Tag="{Binding Path=ExePath}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="{Binding Path=OnButtonClicked}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
的儿童视图模型持有RelayCommands处理按钮单击事件:现在
private RelayCommand onButtonClicked;
public ICommand OnButtonClicked
{
get
{
return onButtonClicked ??
(onButtonClicked =
new RelayCommand(ObeyOnButtonClicked, CanObeyOnButtonClicked));
}
}
private void ObeyOnButtonClicked()
{
... //Path conversion
Process.Start(pathToExe);
}
private bool CanObeyOnButtonClicked()
{
return true;
}
,我的孩子中查看的代码隐藏,当我添加
DataContext = new SampleItemViewModel();
的构造,按钮点击处理,但文本框全部为空。 当我删除这一行时,文本框被正确填充,但不处理按钮点击。
如何让这两个功能都能正常工作?
编辑:
ParentViewModel:
private ObservableCollection<Item> items;
public ObservableCollection<Item> Items
{
get { return items; }
set
{
items= value;
OnPropertyChanged("Items");
}
}
... //Filling the Collection in Constructor
ChildViewModel只包含上面提到的按钮单击处理。
编辑:
我试过几件事情,但现在我不知道如何从ChildView命令绑定到我的ChildViewModel没有设定我ChildView的DataContext的我ChildViewModel
但我怎么处理的ChildViewModel与数据从收集项目按钮点击事件? – user2198982 2013-03-22 12:02:05
请分享您的viewmodels的相关代码 – mathieu 2013-03-22 12:04:05
删除您的DataContext = new SampleItemViewModel();从你的子视图代码后面,并按照mathieu指令 – blindmeis 2013-03-22 13:36:57