如何将命令添加到 wpf 按钮,该按钮是ItemsControl
并正在修改ItemsSource
itself?
这是我的 XAML:
<ItemsControl ItemsSource="{Binding PluginVMs}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<Button x:Name="btnStampDuplicate"
Content="Duplicate this control"
Command="{Binding ?????????}"/>
<!-- other stuff -->
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
这是我的视图模型:
public ObservableCollection<PluginViewModel> PluginVMs
{
get { return _pluginVMs; }
set
{
if (_pluginVMs != value)
{
_pluginVMs = value;
NotifyPropertyChanged("PluginVMs");
}
}
}
如你看到的PluginVMs
是集合PluginViewModel
。所以我知道可以从btnStampDuplicate
应在内部实施PluginViewModel
.
但是,正如名称重复所暗示的那样,我想制作当前生成的重复副本PluginViewModel
代替PluginVMs
。提供这种功能的最佳方法是什么btnStampDuplicate
?
没有必要在每个项目中都有一个命令。您可以使用 CommandParameter 传递一个重复源的项目
在 DataTemplate 内部使用 ElementName 绑定命令来访问更高级别的 DataContext
View
<ItemsControl Name="ListPlugins" ItemsSource="{Binding PluginVMs}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<Button x:Name="btnStampDuplicate"
Content="duplicate"
CommandParameter={Binding Path=.}
Command="{Binding Path=DataContext.DupeCmd, ElementName=ListPlugins}"
/>
<!-- other stuff -->
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
视图模型
public class Vm
{
public ObservableCollection<PluginViewModel> PluginVMs
{
get { return _pluginVMs; }
set
{
if (_pluginVMs != value)
{
_pluginVMs = value;
NotifyPropertyChanged("PluginVMs");
}
}
}
public ICommand DupeCmd { get; private set; }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)