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

时间:2013-04-25 14:26:49

标签: c# wpf xaml mvvm

我还在学习WPF Binding并且一直在努力解决这个问题。我在ViewModel中有一个枚举存储,如下所示:

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'

但是,如果我将枚举移出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加载VM:

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

感谢。

1 个答案:

答案 0 :(得分:3)

这项工作很好:

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

您使用此代码运行项目? 如果您不构建项目,WPF设计器可以显示此错误//'Type was not found.',因为它没有看到枚举的类型。