C# 为什么我的WPF命令没有开火?
我有这个XAML:C# 为什么我的WPF命令没有开火?,c#,wpf,mvvm,C#,Wpf,Mvvm,我有这个XAML: <UserControl x:Class="Foo.UserControls.Bar" x:Name="FooBar" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Stac
<UserControl x:Class="Foo.UserControls.Bar"
x:Name="FooBar"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel>
<WrapPanel Margin="4,0,0,0">
<Button Command="{Binding Path=CreateCommand, ElementName=FooBar}">
<TextBlock>Create</TextBlock>
</Button>
通过调试器和控制台日志记录,它似乎永远不会启动。奇怪的是,绑定似乎很好,因为它不会将任何错误记录到输出中。如果我故意破坏绑定,我会得到一个绑定错误,但是使用上面的绑定,我不会得到任何错误,但它永远不会触发。尝试放置
CreateCommand=new DelegateCommand(Create)代码>在初始化组件()之前
创建命令后,尝试在构造函数中设置DataContext=this
。@默认情况下,控件在InitializeComponent()
方法中创建其绑定,此时CreateCommand未被分配。用户需要在InitializeComponent()
之前移动分配,或者在分配命令后引发属性更改事件。
namespace Foo.UserControls
{
public partial class Bar : UserControl
{
public DelegateCommand CreateCommand { get; private set; }
public Bar()
{
InitializeComponent();
CreateCommand = new DelegateCommand(Create);
}
private void Create(object action)
{
Console.WriteLine("foo");
}
}
}