如何在切换按钮IsChecked上更改属性的值?

时间:2018-04-12 12:37:02

标签: c# wpf xaml mvvm inotifypropertychanged

在我的基类中,我有以下内容:

    private string groupOperator;
    public string GroupOperator
    {
        get
        {
            this.groupOperator = ConvertOperatorToString();
            return this.groupOperator;
        }
        set
        {
            this.groupOperator = value;
            OnPropertyChanged("GroupOperator");
        }
    }

    private bool isOrOperator = false;
    public bool IsOrOperator
    {
        get
        {
            return this.isOrOperator;
        }
        set
        {
            this.isOrOperator = value;
            OnPropertyChanged("IsOrOperator");
        }
    }

    public string ConvertOperatorToString()
    {
        if (IsOrOperator)
        {
            return "Or";
        } 

        else
        {
            return "And";
        }

    }

我正在使用TextBlock在我的XAML中显示GroupOperator。理想的功能是根据是否切换切换按钮,使字符串值在And / Or之间变化。现在,它根本没有改变TextBlock,我想知道我做错了什么。

这是我的XAML:

<TextBlock Style="{StaticResource TextBlockBaseStyling}" VerticalAlignment="Center" Text="{Binding GroupOperator, UpdateSourceTrigger=PropertyChanged}"/>
                                            <ToggleButton x:Name="OperatorSwitch" Style="{StaticResource ToggleViewSwitch}"
                                            Visibility="{Binding IsToggleVisible, UpdateSourceTrigger=PropertyChanged}"
                                            IsChecked="{Binding IsOrOperator, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
                                        </Grid>
                                    </Grid>
                                    <ItemsPresenter x:Name="ItemsHost" Grid.ColumnSpan="2" Grid.Column="1" Grid.Row="1"/>
                                </Grid>
                            </Border>
                        </Grid>
                        <TextBlock Style="{StaticResource TextBlockBaseStyling}"

                                   Text="{Binding ParentGroup.GroupOperator, UpdateSourceTrigger=PropertyChanged}"
                                   Visibility="{Binding IsOperatorVisible, Converter={StaticResource BooleanConverter}, UpdateSourceTrigger=PropertyChanged}"
                                   VerticalAlignment="Center" HorizontalAlignment="Center" Margin="0, 10, 0, 0"/>
                    </StackPanel>

注意:正确处理PropertyChange时,ParentGroup.GroupOperator和GroupOperator实际上应该是相同的值。

1 个答案:

答案 0 :(得分:1)

你的代码应该是

public string GroupOperator
{
    get
    {
        return ConvertOperatorToString();
    }
}

private bool isOrOperator = false;
public bool IsOrOperator
{
    get
    {
        return this.isOrOperator;
    }
    set
    {
        this.isOrOperator = value;
        OnPropertyChanged("IsOrOperator");
        OnPropertyChanged("GroupOperator");
    }
}

设置运算符值会更改多个属性,您需要通知更改属性更改时的更改属性