WPF Binding with 2 Checkboxes

坚强是说给别人听的谎言 提交于 2019-12-12 02:23:01

问题


I am trying to bind 2 checkboxes together so that when one is checked, the other is checkbox is disabled.

Right now I am just trying to get anything to work. Bind one so that if it is not checked, the other elements that it is bound to is disabled. Eventually I want it to be the inverse of whatever is checked(To only have one or the other checked.) I know I will have to use a converter for that. The IsChecked binding is working properly, just not the IsEnabled property. Any help would be greatly appreciated.

<GridViewColumn.CellTemplate>
     <DataTemplate>
          <Grid HorizontalAlignment="Stretch">
               <CheckBox Name="kioskRequiredCB"  IsChecked="{Binding DefaultKioskAsRequired}" IsEnabled="{Binding ElementName=kioskHiddenCB, Path=IsChecked,Mode=TwoWay}" />
           </Grid>
      </DataTemplate>
 </GridViewColumn.CellTemplate>

<GridViewColumn.CellTemplate>
     <DataTemplate>
          <Grid HorizontalAlignment="Stretch">
                <CheckBox Name="kioskHiddenCB"  IsChecked="{Binding DefaultKioskAsHidden}" IsEnabled="{Binding ElementName=kioskRequiredCB, Path=IsChecked,Mode=TwoWay}" />
          </Grid>
      </DataTemplate>
 </GridViewColumn.CellTemplate>

回答1:


Both of your Checkboxes are declared inside templates, which are separate name scopes, so can't see each other's names to do an ElementName Binding. To get around this you need to bind to data that's common to the two, which it looks like you already have:

<GridViewColumn.CellTemplate>
     <DataTemplate>
          <Grid HorizontalAlignment="Stretch">
               <CheckBox Name="kioskRequiredCB"  IsChecked="{Binding DefaultKioskAsRequired}"
                         IsEnabled="{Binding DefaultKioskAsHidden, Converter={StaticResource SomeInvertingBooleanConverter}" />
           </Grid>
      </DataTemplate>
 </GridViewColumn.CellTemplate>

<GridViewColumn.CellTemplate>
     <DataTemplate>
          <Grid HorizontalAlignment="Stretch">
                <CheckBox Name="kioskHiddenCB"  IsChecked="{Binding DefaultKioskAsHidden}"
                          IsEnabled="{Binding DefaultKioskAsRequired, Converter={StaticResource SomeInvertingBooleanConverter}}" />
          </Grid>
      </DataTemplate>
 </GridViewColumn.CellTemplate>


来源:https://stackoverflow.com/questions/15691884/wpf-binding-with-2-checkboxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!