2009-06-18 8 views
7

Comment lier le membre IsChecked d'un CheckBox à une variable membre de mon formulaire?WPF Databinding CheckBox.IsChecked

(je me rends compte que je peux y accéder directement, mais je suis en train d'apprendre et databinding WPF)

ci-dessous est ma tentative avortée d'obtenir ce travail.

XAML:

<Window x:Class="MyProject.Form1" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
Title="Title" Height="386" Width="563" WindowStyle="SingleBorderWindow"> 
<Grid> 
    <CheckBox Name="checkBoxShowPending" 
       TabIndex="2" Margin="0,12,30,0" 
       Checked="checkBoxShowPending_CheckedChanged" 
       Height="17" Width="92" 
       VerticalAlignment="Top" HorizontalAlignment="Right" 
       Content="Show Pending" IsChecked="{Binding ShowPending}"> 
    </CheckBox> 
</Grid> 
</Window> 

code:

namespace MyProject 
{ 
    public partial class Form1 : Window 
    { 
     private ListViewColumnSorter lvwColumnSorter; 

     public bool? ShowPending 
     { 
      get { return this.showPending; } 
      set { this.showPending = value; } 
     } 

     private bool showPending = false; 

     private void checkBoxShowPending_CheckedChanged(object sender, EventArgs e) 
     { 
      //checking showPending.Value here. It's always false 
     } 
    } 
} 

Répondre

12
<Window ... Name="MyWindow"> 
    <Grid> 
    <CheckBox ... IsChecked="{Binding ElementName=MyWindow, Path=ShowPending}"/> 
    </Grid> 
</Window> 

note i ajouté un nom à <Window>, et a changé la liaison dans votre CheckBox. Vous devrez également implémenter ShowPending en tant que DependencyProperty si vous souhaitez qu'il soit mis à jour lorsqu'il est modifié.

+1

Si la propriété est dans un 'ViewModel' plutôt que dans' View' lui-même, comment feriez-vous la liaison? – Pat

+3

Si vous utilisez un ViewModel, vous devez généralement définir votre DataContext dans votre View (ou dans le XAML) à votre ViewModel, et simplement faire 'IsChecked =" {Binding ShowPending} "' –

2

Additif au @ réponse de Will: c'est ce que votre DependencyProperty pourrait ressembler (créée à l'aide Dr. WPF's snippets):

#region ShowPending 

/// <summary> 
/// ShowPending Dependency Property 
/// </summary> 
public static readonly DependencyProperty ShowPendingProperty = 
    DependencyProperty.Register("ShowPending", typeof(bool), typeof(MainViewModel), 
     new FrameworkPropertyMetadata((bool)false)); 

/// <summary> 
/// Gets or sets the ShowPending property. This dependency property 
/// indicates .... 
/// </summary> 
public bool ShowPending 
{ 
    get { return (bool)GetValue(ShowPendingProperty); } 
    set { SetValue(ShowPendingProperty, value); } 
} 

#endregion 
0

Vous devez faire votre mode de liaison comme TwoWay:

<Checkbox IsChecked="{Binding Path=ShowPending, Mode=TwoWay}"/>