How to bind boolean to GridViewColumn checkboxes (have code but doesn't work)?
I am trying to bind a bool value to checkboxes in a GridViewColumn
, but it doesn't work. I even tried just returning false, but the chec开发者_如何学Ckboxes still look enabled. It only works if I type "False" into the xaml.
The binded property is:
public bool HasPermissions
{
get { return this.UserPrivileges == UserPrivileges.FullAccess; }
}
Current value of this.UserPrivileges
is not UserPrivileges.FullAccess
.
Xaml code:
<Window x:Class="EffectsWindow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Effects Manager"
Width="800"
Height="500"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
<DockPanel VerticalAlignment="Stretch">
<DockPanel.Resources>
<ListView x:Name="EffectsListView"
ItemsSource="{Binding AllEffects}">
<ListView.View>
<GridView>
<GridViewColumn Width="50" Header="Override">
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox Margin="0"
HorizontalAlignment="Center"
IsEnabled="{Binding HasPermission}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</DockPanel>
</Window>
EDIT: Current property code:
public bool HasPermissions
{
get { return this.UserPermissions == UserPermissions.FullAccess; }
set { this.RaisePropertyChanged ( "HasPermissions" ); }
}
Think about the problem in your updated property: that property has no backing field, its getter returns the result of comparing a different property with UserPermissions.FullAccess
. Therefore it can never be set.
The thing to focus on is, when does the UI need to be notified that the value returned by HasPermissions
has changed? Well, when can that value change? When the value of this.UserPermissions
changes, right?
Assuming this.UserPermissions
is itself a property with a setter, its setter is the place to call RaisePropertyChanged("HasPermissions")
. That will tell the UI that, even if it doesn't bind to UserPermissions
directly, the property it does bind to must be re-evaluated.
Update: Regarding your comment, IsChecked
is indeed the CheckBox property you should bind HasPermissions
to if you want the box's checked state to indicate that the user has permission.
Update the 2nd: It sounds like you want to access a property of the Window's DataContext from a visual child (the ListBox). You can use a RelativeSource binding to achieve that, like so:
<CheckBox Margin="0"
HorizontalAlignment="Center"
IsEnabled="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.HasPermission}"/>
That somewhat clunky notation will find the nearest parent element to the CheckBox in the visual tree that is of type Window, and bind to its DataContext property to find HasPermission.
精彩评论