0

因此,我花了大约两个小时将头撞在桌子上,尝试了所有我能想到的绑定到自定义控件上的属性的方法,但都不起作用。如果我有这样的事情:

<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它永远不会被命中,有什么关系?

4

1 回答 1

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}

此外,如果任何绑定有问题:有一些方法可以调试它们

于 2012-07-24T18:36:21.303 回答