ToggleButton始终是真正的MVVM WPF

本文关键字:MVVM WPF ToggleButton | 更新日期: 2023-09-27 18:25:51

我有一个小问题。切换按钮有三种状态——两种已选中,一种未选中,但它总是处于选中状态。我不知道为什么。

XAML:

<ToggleButton Grid.Row="0" Grid.Column="1" Style="{DynamicResource MetroCircleToggleButtonStyle}" IsChecked="{Binding Path=RepeatChecked}" Command="{Binding Path=RepeatCommand}">
            <Image Source="../Ressources/repeat.png"></Image>
</ToggleButton>

C#:

private void RepeatFunction()
        {
            if (!this.RepeatChecked)
            {
                Console.WriteLine("Not checked");
                this.RepeatChecked = true;
                this.stateRepeat = StateRepeat.ONE;
            }
            else if (this.RepeatChecked && this.stateRepeat == StateRepeat.ONE)
            {
                Console.WriteLine("Not checked - 2");
                this.RepeatChecked = true;
                this.stateRepeat = StateRepeat.ALL;
            }
            else if (this.RepeatChecked)
            {
                Console.WriteLine("Checked");
                this.RepeatChecked = false;
                this.stateRepeat = StateRepeat.NONE;
            }
        }

控制台写入始终处于选中状态。我真的不明白。

编辑:

this.stateRepeat = StateRepear.NONE;
this.RepeatCommand = new CommandProvider(obj => RepeatFunction());

ToggleButton始终是真正的MVVM WPF

问题是,在单击切换按钮时,您总是将RepeatChecked设置为false/true,这与IsChecked绑定,后者会更新切换状态集unchecked/checked;所以将已检查的更改改为未检查的更改,并将未检查的修改改为检查。在所有三个条件下注释行并运行流,您将看到所有条件都在工作。

private void RepeatFunction()
{
    if (!this.RepeatChecked)
    {
        Console.WriteLine("Not checked");
        ////this.RepeatChecked = true;
        this.stateRepeat = StateRepeat.ONE;
    }
    else if (this.RepeatChecked && this.stateRepeat == StateRepeat.ONE)
    {
        Console.WriteLine("Not checked - 2");
        ////this.RepeatChecked = true;
        this.stateRepeat = StateRepeat.ALL;
    }
    else if (this.RepeatChecked)
    {
        Console.WriteLine("Checked");
        ////this.RepeatChecked = false;
        this.stateRepeat = StateRepeat.NONE;
    }
}