WPF Custom Attached Property in DataTrigger
开发者_运维技巧I've looked at similar questions here on SO and wasn't able to get a solution, so here's my deal:
** I Have the following class: **
public static class ControlSecurity
{
public static readonly DependencyProperty IsSecuredProperty =
DependencyProperty.RegisterAttached(
"IsSecured",
typeof (bool),
typeof (FrameworkElement),
new PropertyMetadata(false));
[AttachedPropertyBrowsableForType(typeof(Control))]
public static bool GetIsSecured(FrameworkElement ctl)
{
return (bool)ctl.GetValue(IsSecuredProperty);
}
public static void SetIsSecured(FrameworkElement ctl, bool value)
{
ctl.SetValue(IsSecuredProperty, value);
}
}
As you can surmise, it adds Security:ControlSecurity.IsSecured
to all FrameworkElement
s.
Note: Security:
Points to the namespace all these classes are in (including ControlSecurity
)
So I've implemented this data-template & style for one of my controls:
<DataTemplate x:Key="SecureButtonTemplate">
<StackPanel Orientation="Horizontal">
<Image x:Name="SecureIcon" Source="pack://application:,,,/Resources/Icons/secure.png" Width="16" Height="16" Visibility="Collapsed" />
<ContentPresenter Content="{Binding}" />
</StackPanel>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}, Path=Security:ControlSecurity.IsSecured}" Value="true">
<Setter TargetName="SecureIcon" Property="Visibility" Value="Visible" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
<Style TargetType="{x:Type Button}">
<Setter Property="ContentTemplate" Value="{StaticResource SecureButtonTemplate}" />
</Style>
The problem here lies in the binding on the DataTrigger
:
{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}, Path=Security:ControlSecurity.IsSecured}
The idea is, I want to find the parent button, and bind to it's Security:ControlSecurity.IsSecured
attached property I've defined.
I've tried about 10 different variations on this binding, and I keep getting a binding error somewhat like this:
System.Windows.Data Error: 40 : BindingExpression path error: 'Security:ControlSecurity' property not found on 'object' ''Button' (Name='')'. BindingExpression:Path=Security:ControlSecurity.IsSecured; DataItem='Button' (Name=''); target element is 'ContentPresenter' (Name=''); target property is 'NoTarget' (type 'Object')
I'm stumped at this point, and would love some insight from the WPF gurus out there.
Just add parenthesis :
Path=(Security:ControlSecurity.IsSecured)
精彩评论