如何在WPF中为MVVM实现多状态CheckBox

时间:2011-06-10 13:30:50

标签: wpf mvvm checkbox

我需要在WPF中需要多状态复选框 ...

另外,因为我正在使用MVVM所以处理绑定和命令应该遵循相同的方式,因为我将在我的视图中使用它。

我在DotnetNuke(在ASP.NET中制作)中看到了一个Multistate复选框,但是如何在WPF中创建它

这方面的一些意见将有所帮助

一些例子会很棒......

2 个答案:

答案 0 :(得分:2)

复选框具有特定功能(已选中,未选中且可选择不确定)。

根据您的评论,我认为将其作为按钮进行操作是最简单的。我现在没有时间来测试一个实际的例子,但是这里有一些伪代码可以帮助你:

<强> XAML

<Button Command="{Binding ToggleDecisionState}">
    <Button.Content>
        <Image Source="{Binding CurrentDecisionIcon}" />
    <Button.Content>
</Button>

ViewModel(省略MVVM实施细节)

enum Decisions
{
    Agree,
    Disagree,
    Maybe,
    DoNotKnow
};

public Decisions CurrentDecision
{
    get {}
    set {}
}

public RelayCommand ToggleDecisionStateCommand
{
       // In here, call code to execute toggle
       if (mCurrentDecision == Decisions.DoNotKnow)
           CurrentDecision = Decisions.Agree;
       else
           CurrentDecision += 1;       
}

public ImageSource CurrentDecisionIcon
{
    get
    {
        ImageSource img = [some default image];
        switch (mCurrentDecision)
        {
            case Decisions.Agree:
                img = [path to Agree icon];
                break;

            // Other cases here
        }

        return img;
    }
}

答案 1 :(得分:1)

如果要使用3状态复选框,则必须更改后面的布尔值(在ViewModel中) 布尔?类型。

  public bool? IsEnabled { get; set; }

并为CheckBox设置此属性

  IsThreeState = True;