【问题标题】:Pass Enum value as CommandParameter when the Enum is in the ViewModel当 Enum 在 ViewModel 中时,将 Enum 值作为 CommandParameter 传递
【发布时间】:2013-04-25 14:26:49
【问题描述】:

我仍在学习 WPF 绑定并且已经为此苦苦挣扎了一段时间。我在 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 缺少某些内容?

VM 是通过 DataContext 加载的:

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

谢谢。

【问题讨论】:

    标签: c# wpf xaml mvvm


    【解决方案1】:

    这项工作很好:

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

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

    【讨论】:

    • 谢谢,这确实有效!那么有没有办法抑制Desginer中的错误?否则,我将无法看到视图。
    • 谢谢。没有骰子。尝试构建,清理,重建,似乎没有得到它。如果我想使用设计器,似乎我必须在命名空间中使用它:/。这是VS2010,VS2012用WPF会更好吗?
    猜你喜欢
    • 2016-02-05
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-04
    相关资源
    最近更新 更多