2009-06-18 79 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}"/>