2012-07-18 168 views
0

我创建了一个自己的ComboBoxItem。这里我简化了代码。 ComboBoxItem包含一个CheckBox。不能绑定MyCombobox和绑定属性

ComboBoxItem控制XAML:

<ComboBoxItem x:Class="WpfApplication1.MyCombobox" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      Height="50" 
      Width="200"> 
    <!-- ... --> 
    <StackPanel> 
     <CheckBox IsChecked="{Binding Path=IsCheckboxChecked}" IsEnabled="{Binding Path=IsCheckboxEnabled}"> 
      <CheckBox.LayoutTransform> 
       <ScaleTransform ScaleX="1" ScaleY="1" /> 
      </CheckBox.LayoutTransform> 
     </CheckBox> 
     <!-- ... --> 
    </StackPanel> 
</ComboBoxItem> 

ComboBoxItem控制C#(代码后面)

public partial class MyCombobox 
{ 
    public MyCombobox() 
    { 
     InitializeComponent(); 
     DataContext = this; 

     //Defaults 
     IsCheckboxChecked = false; 
     IsCheckboxEnabled = true; 

     //... 
    } 

    //... 

    public string Text { get; set; } 

    public bool IsCheckboxChecked { get; set; } 

    public bool IsCheckboxEnabled { get; set; } 

    //... 
} 

,我有这么:

<WpfApplication1:MyCombobox IsCheckboxChecked="{Binding Path=IsMyCheckBoxChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsCheckboxEnabled="{Binding Path=IsMyCheckBoxEnabled, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" Text="Write your Text here" /> 

当我运行我的应用程序我得到这个错误:

A fatal error occurred: a 'Binding' cannot be set on the 'IsCheckboxChecked' property of type 'MyCombobox'. A 'Binding' can only be set on a Dependency Property of a DependencyObject

我做错了什么?

+0

错误细节让你知道问题是什么,你需要做IsCheckboxChecked一个DependencyProperty才能使用绑定。 – user7116 2012-07-18 14:40:11

回答

2

以及错误是相当清楚的:你必须让你的IsCheckboxChecked领域DP:中

public static readonly DependencyProperty IsCheckboxCheckedProperty = DependencyProperty.Register("IsCheckboxChecked", typeof(bool), typeof(MyComboBox)); 
public bool IsCheckboxChecked 
{ 
    get { return (bool)GetValue(IsCheckboxCheckedProperty); } 
    set { SetValue(IsCheckboxCheckedProperty, value); } 
} 

代替:

public bool IsCheckboxChecked { get; set; } 

但这也意味着你必须让你的MycomboBox类继承DependencyObject类:

public partial class MyCombobox : DependencyObject 

我的建议是:http://msdn.microsoft.com/en-gb/library/ms752347.aspx