无法绑定MyCombobox和绑定属性

时间:2012-07-18 14:38:21

标签: c# wpf binding

我创建了一个自己的ComboBoxItem。在这里,我简化了代码。 ComboBoxItem包含一个CheckBox。

ComboBoxItem Control 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 Control 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" />

当我运行我的应用程序时,我收到此错误:

  

发生致命错误:无法设置'绑定'   “IsCheckboxChecked”属性类型为“MyCombobox”。 '绑定'可以   只能在DependencyObject的依赖属性上设置

我做错了什么?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

你必须让你的财产'可绑定'。

看看这个:http://www.wpftutorial.net/dependencyproperties.html

相关问题