web-dev-qa-db-fra.com

Liaison de données de propriété attachée WPF

J'essaie d'utiliser la liaison avec une propriété attachée. Mais je ne peux pas le faire fonctionner.

public class Attached
{
    public static DependencyProperty TestProperty =
        DependencyProperty.RegisterAttached("TestProperty", typeof(bool), typeof(Attached),
        new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.Inherits));

    public static bool GetTest(DependencyObject obj)
    {
        return (bool)obj.GetValue(TestProperty);
    }

    public static void SetTest(DependencyObject obj, bool value)
    {
        obj.SetValue(TestProperty, value);
    }
}

Le code XAML:

<Window ...>
    <StackPanel local:Attached.Test="true" x:Name="f">
        <CheckBox local:Attached.Test="true" IsChecked="{Binding (local:Attached.Test), Mode=TwoWay, RelativeSource={RelativeSource Self}}" />
        <CheckBox local:Attached.Test="true" IsChecked="{Binding (local:Attached.Test), Mode=TwoWay}" />
    </StackPanel>
</Window>

Et l'erreur contraignante:

System.Windows.Data Error: 40 : BindingExpression path error: '(local:Attached.Test)' property not found on 'object' ''StackPanel' (Name='f')'. BindingExpression:Path=(local:Attached.Test); DataItem='StackPanel' (Name='f'); target element is 'CheckBox' (Name=''); target property is 'IsChecked' (type 'Nullable`1')
60
Daniel Bişar

Croyez-le ou non, ajoutez simplement Path= et utilisez des parenthèses lors de la liaison à une propriété attachée:

IsChecked="{Binding Path=(local:Attached.Test), Mode=TwoWay, RelativeSource={RelativeSource Self}}"

En outre, votre appel à RegisterAttached doit passer dans "Test" comme nom de propriété, pas "TestProperty".

156
Kent Boogaart

J'aurais préféré poster ceci comme un commentaire sur la réponse de Kent mais comme je n'ai pas assez de représentant pour le faire ... je voulais juste souligner que depuis WPF 4.5, en ajoutant Path= n'est plus nécessaire. Cependant, le nom de la propriété attachée doit toujours être entouré de parenthèses.

18
Livven