2009-06-18 18 views
7

Come collego il membro IsChecked di un CheckBox a una variabile membro nel mio modulo?WPF Databinding CheckBox.IsChecked

(mi rendo conto che posso accedervi direttamente, ma sto cercando di conoscere l'associazione dati e WPF)

Qui di seguito è il mio tentativo fallito per ottenere questo lavoro.

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> 

Codice:

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 
     } 
    } 
} 

risposta

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

nota che ho aggiunto un nome alla <Window>, e ha cambiato il legame nel vostro CheckBox. È necessario implementare ShowPending come DependencyProperty se si desidera che sia in grado di aggiornarsi quando modificati.

+1

Se la proprietà è in un 'ViewModel' piuttosto che nel' View' stesso, come faresti il ​​binding? – Pat

+3

Se si utilizza un ViewModel, in genere si imposta DataContext all'interno della vista (o in XAML) sul ViewModel e si esegue semplicemente 'IsChecked =" {Binding ShowPending} "' –

2

Addendum al @ risposta di Will: questo è ciò che il vostro DependencyProperty potrebbe essere simile (creato utilizzando 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

è necessario effettuare la modalità di rilegatura come TwoWay:

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