C# 自定义命令中的DependencyProperty
我尝试编写一个包装器命令类。我想这样使用它C# 自定义命令中的DependencyProperty,c#,wpf,C#,Wpf,我尝试编写一个包装器命令类。我想这样使用它 <Button Content="Test"> <Button.Command> <local:FileOpenCommand Command="{Binding OpenFile}"/> </Button.Command> </Button> 这始终显示来自DefaultValue命令的消息框。与OpenFile的绑定不起作用。我没有收到BindingExpression错
<Button Content="Test">
<Button.Command>
<local:FileOpenCommand Command="{Binding OpenFile}"/>
</Button.Command>
</Button>
这始终显示来自DefaultValue
命令的消息框。与OpenFile
的绑定不起作用。我没有收到BindingExpression错误,但从未调用Openfile
属性
编辑:主窗口代码
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
public ICommand OpenFile
{
get { return new RelayCommand(
(obj) => MessageBox.Show("I want to see this!")); }
}
}
您的
FileOpenCommand
不是可视化或逻辑树的一部分,因此您没有继承的DataContext
,因此您的绑定无法工作。尝试使用ElementName
或设置显式源代码。记住RelativeSource
遍历树,也不会工作。添加PresentationTraceSources.TraveLevel=High
,自己检查实际问题
但要说清楚,你为什么要这么做?怎么了
<Button Content="Test" Command="{Binding OpenFile}">
</Button>
这似乎应该可以工作,您可以添加OpenFile属性,以及它是如何初始化的吗?@eranotzer我添加了示例主窗口的代码。谢谢您的回答,我明天会检查。你的问题:我喜欢将文件选择的外观与VM层分开的想法,但如果命令包装器不起作用,这是我的选择。记住在命令中调用命令是完全正确的,没有特殊的逻辑。因此,您可以构建一个打开文件对话框的命令,并在选择文件后,启动实际的open命令,该命令直接对文件名进行操作。我尝试使用ElementName
,但我找不到绑定引用'ElementName=Btn'的源代码。BindingExpression:Path=DataContext.OpenFile;。我想我会在OpenFile
中返回一个FileOpenCommand,但是无论如何运行它都会很好。
<Button Content="Test" Command="{Binding OpenFile}">
</Button>