【问题标题】:wpf bindings between two checkboxes两个复选框之间的 wpf 绑定
【发布时间】:2014-05-07 05:53:54
【问题描述】:
  <CheckBox x:Name="cb1" IsChecked="{Binding cb1Enabled}"/>
  <CheckBox x:Name="cb2" IsEnabled="{Binding ElementName=cb1, Path=IsChecked}" IsChecked="{Binding cb2Enabled}">

我有这两个复选框 cb1 和 cb2。两者都绑定到 2 个布尔值。 cb1Enabled 和 cb2Enabled。 如您所见,只有在选中 cb1 并且它的 IsChecked 属性绑定到特定的 bool 依赖属性时才启用 cb2。

一切都很好,但我想在未选中 cb1 时取消选中 cb2,因此将 cb2Enabled 设置为 false。有没有办法做到这一点?

所以我想我可以说我希望 cb2 的 IsChecked 属性绑定到 cb1 的 IsChecked 属性以及 cb2Enabled dp。

【问题讨论】:

  • 回复:您的补充:我认为您不能真正说“cb2 的 IsChecked 属性绑定到 cb1 的 IsChecked 属性”,因为您不想检查 cb1 导致 cb2成为检查...对吗?相反,您希望在 cb1 未选中时触发。

标签: c# wpf


【解决方案1】:

这可能最好在视图模型中完成。使用双向绑定:

<CheckBox x:Name="cb1" IsChecked="{Binding cb1Enabled,Mode=TwoWay}"/>

然后,在“cb1Enabled”的设置器中设置“cb2Enabled”属性。例如:

public bool cb1Enabled
{
    get { return bool _cb1Enabled; }
    set
    {
        _cb1Enabled = value;
        if (!_cb1Enabled)
            cb2Enabled = false;
        RaisePropertyChanged();
    }
}
private bool _cb1Enabled;

如果您不喜欢上述内容,仅 XAML 的替代方法是在 UncheckedChangePropertyAction 上使用事件触发器:

<CheckBox x:Name="cb1" IsChecked="{Binding cb1Enabled}">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Unchecked">
            <ei:ChangePropertyAction TargetObject="{Binding}" PropertyName="cb2Enabled" 
                                     Value="False" 
                                     />
        </i:EventTrigger EventName="Unchecked">
    </i:Interaction.Triggers>
</CheckBox>

【讨论】:

  • 非常感谢,稍作改动:
猜你喜欢
  • 2015-03-28
  • 2010-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-27
  • 2014-08-23
  • 1970-01-01
相关资源
最近更新 更多