c# - 从 ContentControl 中的按钮触发命令?

标签 c# wpf mvvm mvvm-light contentcontrol

我是 WPF 的新手,我正在尝试在 ContentControl 中动态添加一个按钮,它应该在单击时触发一个命令。我正在使用 MVVMLight 来处理命令。

下面我有一个有两个按钮的例子。顶部按钮直接放置在 StackPanel 中。此按钮按预期触发命令。

第二个按钮放置在 ContentControl 中。它显示正确,但单击按钮时命令不会触发。 我假设这是因为 Binding 不会通过 DataTemplate 向下传输,但如果我使用常规命令而不是 MVVMLight RelayCommand,它似乎可以工作。

我不想删除框架,所以我想知道是否有人知道如何修复它?谢谢

<Window x:Class="ContentControlExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:ContentControlExample.ViewModel">

    <Window.DataContext>
        <vm:MainViewModel />
    </Window.DataContext>

    <Window.Resources>
        <DataTemplate x:Key="MyButton" >
            <Button Content="SUBMIT" Command="{Binding MyCommand}" Width="200" Height="50"/>
        </DataTemplate>
    </Window.Resources>

    <StackPanel>

        <!--When this button is clicked, the Command executes as expected-->
        <Button Content="SUBMIT" Command="{Binding MyCommand}" Width="200" Height="50"/>


        <!--Nothing happens when this button is clicked-->
        <ContentControl ContentTemplate="{StaticResource MyButton}"/>
    </StackPanel>
</Window>

这是带有命令的 ViewModel:

public class MainViewModel : ViewModelBase
{
        public ICommand MyCommand { get; private set; }

        public MainViewModel()
        {
            MyCommand = new RelayCommand(MyCommand_Executed, MyCommand_CanExecute);
        }

        private bool MyCommand_CanExecute()
        {
            return true;
        }

        private void MyCommand_Executed()
        {
            MessageBox.Show("The command executed");
        }
    }

最佳答案

这里的问题是 ContentTemplate 中的隐式 DataContext 是 Content 并且尚未设置任何内容。您需要将 Content 设置为一些 Binding 以桥接当前在可视化树中的 DataContext,如下所示:

<ContentControl ContentTemplate="{StaticResource MyButton}" Content="{Binding}"/>

关于c# - 从 ContentControl 中的按钮触发命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33271813/

相关文章:

c# - Unity定位与Update在功能上的不同

c# - 我们可以在 C# 文件中使用在 .asp 文件中创建的类吗

c# - 如何在 WPF 中锚定控件?

c# - 当另一个类中的先决条件属性发生更改时,为依赖属性提高 PropertyChanged?

c# - 在 xaml 中使用键绑定(bind)捕获一系列字符

wpf - 如果我创建一个 ViewModel,我是否需要以 MVVM 模式为其创建模型?

c# - 如何检测我的应用程序是否在 Windows 10 上运行

c# - 将 KeyUp 作为参数传递 WPF 命令绑定(bind)文本框

WPF 字符串格式={}{0 :N} Error "Expected ' "

c# - 在不阻塞 UI 的情况下在 ViewModel 中加载大量数据