WPF does not seem to find a custom attached property
-
19-09-2019 - |
Question
I am trying to bind a property (Button.Background) to a property on my custom attached property.
In a C# file I have
public static class Square
{
public static readonly DependencyProperty PlayerProperty =
DependencyProperty.RegisterAttached
(
name : "Player",
propertyType : typeof(Player),
ownerType : typeof(UIElement),
defaultMetadata: new FrameworkPropertyMetadata(null)
);
public static Player GetPlayer(UIElement element)
{
return (Player)element.GetValue(PlayerProperty);
}
public static void SetPlayer(UIElement element, Player player)
{
element.SetValue(PlayerProperty, player);
}
// Other attached properties
}
A snippet of my XAML is
<Grid Name="board" Grid.Row="1" Grid.Column="1">
<Grid.Resources>
<Style TargetType="{x:Type Button}">
<Setter Property="Height" Value="20" />
<Setter Property="Width" Value="20" />
<Setter Property="BorderThickness" Value="3" />
<Setter Property="Background"
Value="{Binding Path=(l:Square.Player).Brush, Mode=OneWay}" />
</Style>
</Grid.Resources>
</Grid>
This is the error I get:
Cannot convert string '(l:Square.Player).Brush' in attribute 'Path' to object of type 'System.Windows.PropertyPath'.
Property path is not valid. 'Square' does not have a public property named 'Player'.
Error at object 'System.Windows.Data.Binding' in markup file 'Gobang.Gui;component/mainwindow.xaml' Line 148 Position 59.
But since Player
is an attached property which is on Square
, the above code should work, right?
Solution
I believe your attached property should designate Square as the owner rather than UIElement.
public static readonly DependencyProperty PlayerProperty =
DependencyProperty.RegisterAttached("Player", typeof(Player),
typeof(Square), new FrameworkPropertyMetadata(null));
OTHER TIPS
I got it to work. Note: its a read-only property, the Helper class HAS TO inherit from DO
public class Helper : DependencyObject
{
public static readonly DependencyPropertyKey IsExpandedKey = DependencyProperty.RegisterAttachedReadOnly(
"IsExpanded", typeof(bool), typeof(Helper), new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.Inherits));
public static readonly DependencyProperty IsExpandedProperty = IsExpandedKey.DependencyProperty;
public static bool GetIsExpanded(DependencyObject d)
{
return (bool)d.GetValue(IsExpandedKey.DependencyProperty);
}
internal static void SetIsExpanded(DependencyObject d, bool value)
{
d.SetValue(IsExpandedKey, value);
}
}
You can't set up a binding in the way that you're doing it - you'll need an instance of either Square
or Player
to bind to that.