WPF数据绑定自定义控件

时间:2012-07-24 18:28:09

标签: wpf data-binding custom-controls

所以我花了大约两个小时的时间将我的头撞在桌子上,试着将我能想到的所有内容绑定到自定义控件上的属性,但没有一个能够正常工作。如果我有这样的事情:

<Grid Name="Form1">
    <mine:SomeControl MyProp="{Binding ElementName=Form1, Path=DataContext.Enable}"/>
    <Button Click="toggleEnabled_Click"/>
</Grid>
public class TestPage : Page
{
    private TestForm _form;

    public TestPage()
    {
        InitializeComponent();
        _form = new TestForm();
        Form1.DataContext = _form;
    }

    public void toggleEnabled_Click(object sender, RoutedEventArgs e)
    {
        _form.Enable = !_form.Enable;
    }
}

TestForm看起来像:

public class TestForm
{
    private bool _enable;

    public event PropertyChangedEventHandler PropertyChanged;

    public bool Enable
    {
       get { return _enable; }
       set { _enable = value; OnPropertyChanged("Enable"); }
    }

    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}

我的控制看起来像:

<UserControl>
    <TextBox Name="TestBox"/>
</UserControl>
public class SomeControl : UserControl
{
    public static readonly DependencyProperty MyPropProperty =
        DependencyProperty.Register("MyProp", typeof(bool), typeof(SomeControl));

    public bool MyProp
    {
        get { return (bool)GetValue(MyPropProperty); }
        set { SetValue(MyPropProperty, value); }
    }

    public SomeControl()
    {
        InitializeComponent();
        DependencyPropertyDescriptor.FromProperty(MyPropProperty)
            .AddValueChanged(this, Enable);
    }

    public void Enable(object sender, EventArgs e)
    {
        TestBox.IsEnabled = (bool)GetValue(MyPropProperty);
    }
}

单击切换按钮时绝对没有任何反应。如果我在Enable回调中放置一个断点,它永远不会被击中,这笔交易是什么?

1 个答案:

答案 0 :(得分:2)

如果Enabled方法不仅仅设置属性,您可以删除它并直接绑定TextBox.IsEnabled

<UserControl Name="control">
    <TextBox IsEnabled="{Binding MyProp, ElementName=control}"/>
</UserControl>

如果你想保留这样一个方法,你应该通过UIPropertyMetadata为依赖属性注册一个属性更改回调。


此绑定也是多余的:

{Binding ElementName=Form1, Path=DataContext.Enable}

DataContext是继承的(如果你没有在UserControl中设置它(你永远不应该这样做!)),所以你可以使用:

{Binding Enable}

此外,如果任何绑定出现问题:There are ways to debug them