【问题标题】:How to add the same command to WPF buttons in ItemsControl如何将相同的命令添加到 ItemsControl 中的 WPF 按钮
【发布时间】:2016-03-14 18:03:45
【问题描述】:

您将如何将命令添加到属于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>

这是我的视图模型:

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

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

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

【问题讨论】:

    标签: c# wpf xaml datatemplate itemscontrol


    【解决方案1】:

    不必在每个项目中都有一个命令。您可以使用 CommandParameter 传递一个欺骗源的项目

    在DataTemplate内部使用ElementName绑定命令来访问更高级别的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>
    

    视图模型

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-13
    • 2017-01-31
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    相关资源
    最近更新 更多