Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 自定义命令中的DependencyProperty_C#_Wpf - Fatal编程技术网

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>