我创建了自己的附属属性,如下所示:
public static class LabelExtension
{
public static bool GetSelectable(DependencyObject obj)
{
return (bool)obj.GetValue(SelectableProperty);
}
public static void SetSelectable(DependencyObject obj, bool value)
{
obj.SetValue(SelectableProperty, value);
}
// Using a DependencyProperty as the backing store for Selectable. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SelectableProperty =
DependencyProperty.RegisterAttached("Selectable", typeof(bool), typeof(Label), new UIPropertyMetadata(false));
}
Run Code Online (Sandbox Code Playgroud)
然后我尝试使用依赖于它的触发器创建一个样式:
<!--Label-->
<Style TargetType="{x:Type Label}">
<Style.Triggers>
<Trigger Property="Util:LabelExtension.Selectable" Value="True">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Label}">
<TextBox IsReadOnly="True" Text="{TemplateBinding Content}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
Run Code Online (Sandbox Code Playgroud)
但我得到一个运行时异常:
Cannot convert the value in attribute 'Property' to object of type 'System.Windows.DependencyProperty'. Error at object 'System.Windows.Trigger' in markup file
Run Code Online (Sandbox Code Playgroud)
如何在样式触发器中访问附加属性的值?我已经尝试使用具有RelativeSource绑定的DataTrigger,但它没有提取值.
ito*_*son 16
您的触发器声明没问题,但您附加的财产声明有一个小问题.依赖项属性的所有者类型需要是声明它的类型,而不是您计划将其附加到的类型.所以这:
DependencyProperty.RegisterAttached("Selectable", typeof(bool), typeof(Label)...
Run Code Online (Sandbox Code Playgroud)
需要改为:
DependencyProperty.RegisterAttached("Selectable", typeof(bool), typeof(LabelExtension)...
^^^^^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11138 次 |
| 最近记录: |