我是WPF的新手,尝试在ContentControl中动态添加一个按钮,并在点击时触发命令。我正在使用MVVMLight来处理命令。以下是两个按钮示例:顶部按钮直接放置在StackPanel中,可以正常触发命令。第二个按钮放置在ContentControl内,虽然显示正确,但点击时未触发命令。我认为这是因为绑定没有通过DataTemplate传递下去。但如果我使用常规命令而不是MVVMLight RelayCommands,则似乎可以工作。我不想删除框架,所以想知道是否有人知道如何解决它?谢谢!
<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");
}
}