2009-06-18 74 views
7

如何将CheckBox的IsChecked成员绑定到表单中的成员变量?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 2010-10-08 16:54:39

2

补遗@ WILL的回答是:这是你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

你必须让你的绑定模式为双向:

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