当Enum在ViewModel中时,将Enum值作为CommandParameter传递

本文关键字:Enum 传递 CommandParameter ViewModel 中时 | 更新日期: 2023-09-27 18:10:48

我还在学习WPF绑定,并且已经为此挣扎了一段时间。我在ViewModel中有一个enum存储,如下所示:

namespace theNamespace
{
    public class frmSetupViewModel
    {
        public enum LocationLabelType {Location, Sample}
        ...
    }
}

我想有一个按钮通过CommandParameter传递一个值,但无法弄清楚如何让它工作。到目前为止,这些是我尝试过的组合:

//When value is inside the frmSetupViewModel, these do not work
CommandParameter="{x:Static local:LocationLabelType.Location}" //'Type  was not found.'
CommandParameter="{x:Static local:frmSetupViewModel+LocationLabelType.Location}" //'Type was not found.'
CommandParameter="{x:Static local:frmSetupViewModel.LocationLabelType.Location}" //'Type was not found.'
CommandParameter="{Binding {x:Static local:LocationLabelType.Location}}" //'Value cannot be null'
CommandParameter="{Binding {x:Static local:frmSetupViewModel+LocationLabelType.Location}}" //'Value cannot be null'
CommandParameter="{Binding {x:Static local:frmSetupViewModel.LocationLabelType.Location}}" //'Value cannot be null'

但是如果我将enum移出VM并像这样移动到名称空间:

namespace theNamespace
{
    public enum LocationLabelType {Location, Sample}
    public class frmSetupViewModel
    {
        ...
    }
}

这个可以正常工作:

//Works when enum is moved to Namespace
CommandParameter="{x:Static local:LocationLabelType.Location}"

我假设我错过了我的CommandParameter的东西?

虚拟机通过DataContext加载:

<Window.DataContext>
    <local:frmSetupViewModel />
</Window.DataContext>

谢谢。

当Enum在ViewModel中时,将Enum值作为CommandParameter传递

这个工作很好:

CommandParameter="{x:Static uiTest:MainWindow+LocationLabelType.Location}"

你用这段代码运行了这个项目?如果您不构建项目,WPF设计器可以显示此错误//'Type was not found.',因为它看不到enum的类型。