2009-11-26 56 views
0

我刚刚遇到这个问题与我的CheckBox数据绑定。该场景是:WPF复选框没有得到检查在启动(数据绑定)

当我初始化用户界面(启动应用程序)时,CheckBox es被取消选中,尽管它们绑定的属性设置为true。当我点击CheckBox时,该属性设置为false,但CheckBox仍显示为未选中状态。从现在开始,数据绑定按预期工作,并且CheckBox与binding属性正确同步。

这里是我的XAML代码:

<ItemsControl ItemsSource="{Binding Path=DisplayTypes}"> 
    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate> 
      <WrapPanel /> 
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate DataType="{x:Type Presentation:TypeDisplayPair}"> 
      <CheckBox IsChecked="{Binding Display}" Margin="3"> 
       <TextBlock Text="{Binding Type}" Foreground="{Binding Color}" /> 
      </CheckBox> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

我的视图模型:

public class TypeDisplayPair : BaseViewModel 
{ 
    private bool display; 
    private readonly Brush color; 

    public TypeDisplayPair(string type, bool display) 
    { 
     Display = display; 
     Type = type; 
     color = BrushGenerator.GetRandomSolidColorBrush(); 
    } 

    public string Type { get; set; } 

    public bool Display 
    { 
     get { return display; } 
     set 
     { 
      display = value; 
      this.FirePropertyChanged(x => x.Display); 
     } 
    } 

    public Brush Color 
    { 
     get { return color; } 
    } 
} 

任何建议表示赞赏,因为我已经花了太多的时间调试这一点,我已经用完了想法。

回答

2

您提供的代码是完全正确的,初始化问题可能来自您指定DataContext的方式。我试过以下内容:

public Window1() 
    { 
     DataContext = this; 
     DisplayTypes = new ObservableCollection<TypeDisplayPair>() 
     { 
      new TypeDisplayPair("Alpha", true), 
      new TypeDisplayPair("Beta", false) 
     }; 

     InitializeComponent(); 
    } 

它按预期工作。