2009-06-18 16 views
7

¿Cómo vincularía el miembro IsChecked de un CheckBox a una variable miembro en mi formulario?WPF Databinding CheckBox.IsChecked

(me di cuenta que puedo acceder a ella directamente, pero estoy tratando de aprender acerca de enlace de datos y WPF)

A continuación es mi intento fallido de conseguir este trabajo.

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> 

Código:

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

Respuesta

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

Nota i añadir un nombre a <Window>, y cambió la unión en su casilla de verificación. También deberá implementar ShowPending como DependencyProperty si desea que se actualice cuando se modifique.

+1

Si la propiedad es en un 'ViewModel' en lugar de' View', ¿cómo harías el enlace? – Pat

+3

Si usa un ViewModel, normalmente establecería su DataContext dentro de su View (o en el XAML) a su ViewModel, y simplemente haría 'IsChecked =" {Binding ShowPending} "' –

2

Adición al @ respuesta de Will: esto es lo que su DependencyProperty podría parecerse (creados con 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

usted debe hacer su modo de unión como TwoWay:

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