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メソッドがpropertouを設定する以上のことをしない場合は、それをドロップして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 に答える