2009-06-18 2 views
7

Как связать член IsChecked из CheckBox с переменной-членом в моей форме?WPF Databinding CheckBox.IsChecked

(я понимаю, что я могу получить доступ к нему напрямую, но я пытаюсь узнать о привязки данных и WPF)

Ниже моя неудачная попытка получить эту работу.

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> 

Код:

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

ответ

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

Примечание я добавил имя <Window>, и изменил связывании в вашем CheckBox. Вам нужно будет реализовать ShowPending как DependencyProperty, если вы хотите, чтобы он мог обновляться при изменении.

+1

Если свойство является в 'ViewModel', а не в' View', как бы вы сделали привязку? – Pat

+3

Если вы используете ViewModel, вы обычно устанавливаете свой DataContext в своем представлении (или в XAML) в ViewModel и просто выполняете 'IsChecked = {{Binding ShowPending}" ' –

2

Добавление к @ ответ Уилла: это то, что ваш DependencyProperty может выглядеть (созданные с помощью 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

Вы должны сделать свой режим связывания, как TwoWay:

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