c# - 如何向 ItemsControl 中的 WPF 按钮添加相同的命令

标签 c# wpf xaml datatemplate itemscontrol

如何将命令添加到属于 ItemsControl 一部分并修改 ItemsSource 本身的 wpf 按钮?

这是我的 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>

这是我的 View 模型:

public ObservableCollection<PluginViewModel> PluginVMs
{
    get { return _pluginVMs; }
    set
    {
        if (_pluginVMs != value)
        {
            _pluginVMs = value;
            NotifyPropertyChanged("PluginVMs");
        }
    }
}

如您所见,PluginVMsPluginViewModel 的集合。所以我知道从 btnStampDuplicate 中可用的命令应该在 PluginViewModel 内部实现。

但是,正如名称重复所示,我想在 PluginVMs 内复制当前生成的 PluginViewModel。为 btnStampDuplicate 提供此类功能的最佳方法是什么?

最佳答案

没有必要在每个项目中都有一个命令。您可以使用 CommandParameter 传递一个重复源的项目

在 DataTemplate 内部使用 ElementName 绑定(bind)命令来访问更高级别的 DataContext

查看

<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>

View 模型

public class Vm
{
    public ObservableCollection<PluginViewModel> PluginVMs
    {
        get { return _pluginVMs; }
        set
        {
            if (_pluginVMs != value)
            {
                _pluginVMs = value;
                NotifyPropertyChanged("PluginVMs");
            }
        }
    }

    public ICommand DupeCmd { get; private set; }
}

关于c# - 如何向 ItemsControl 中的 WPF 按钮添加相同的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35994796/

相关文章:

c# - 关于设置和部署的 Crystal Report 集成问题

c# - Winforms WPF Interop - Wpf 控件呈现为非事件状态

c# - WPF 用户控件中的自定义属性

c# - 使用 XAML 的 Setter 上的“#33333 3' is not a valid value for the ' System.Windows.Controls.Border.BorderBrush”属性

c# - 为 wpf 应用程序中的所有控件启用/禁用工具提示

c# - 如何在 Xamarin.Forms 的代码中使用 TimeSpan 字符串格式?

c# - 找不到预期的}

wpf - DataGrid RowStyle - DataTrigger 中的绑定(bind)值

c# - WPF DataGridTextColumn 绑定(bind)不接受小数

xaml - 忽略 XamlWriter.Save 中的不可序列化对象