2012-07-18 267 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