【发布时间】:2011-11-04 22:54:30
【问题描述】:
我有一个扩展 WPF TextBox 控件的简单控件。基本思想是通过启用TextBox 在其为空时在其中显示自己的标签来节省 UI 中的空间。
我在其中声明了一个名为Label 的DependencyProperty,并将TextBox.Template 属性设置为ControlTemplate。 ControlTemplate 是默认的 Windows Aero XAML,在显示 TextBox.Text 属性值的控件后面添加了一个 TextBlock。它的Visibility 属性与Converter 绑定,以便在Text 属性为空时可见。 (有很多而且大多无趣,所以请原谅滚动条)。
<ControlTemplate x:Key="LabelTextBoxTemplate" TargetType="{x:Type TextBoxBase}" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Aero="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero">
<Aero:ListBoxChrome Background="{TemplateBinding Panel.Background}" BorderBrush="{TemplateBinding Border.BorderBrush}" BorderThickness="{TemplateBinding Border.BorderThickness}" RenderMouseOver="{TemplateBinding UIElement.IsMouseOver}" RenderFocused="{TemplateBinding UIElement.IsKeyboardFocusWithin}" Name="Border" SnapsToDevicePixels="True">
<Grid>
<TextBlock Text="{Binding Label, ElementName=This}" Visibility="{Binding Text, ElementName=This, Converter={StaticResource StringToVisibilityConverter}}" SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" FontWeight="Normal" FontStyle="Italic" Foreground="#99000000" Padding="3,0,0,0" />
<ScrollViewer Name="PART_ContentHost" SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
</Grid>
</Aero:ListBoxChrome>
<ControlTemplate.Triggers>
<Trigger Property="UIElement.IsEnabled" Value="False">
<Setter TargetName="Border" Property="Panel.Background" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" />
<Setter Property="TextElement.Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
(控件的Name属性设置为This进行绑定)
所以无论如何,这一切都很好,但我想知道我是否可以用附加属性替换这个功能。我创建了一个名为Label 的附加属性,并添加了一个在设置属性时调用的回调委托。在这种方法中,我计划从Application.Resources 中找到ControlTemplate 并将TextBox.Template 属性设置为它...我找不到访问ControlTemplate 的方法所以这是我的第一个问题。
如何从附加属性访问 App.xaml 中 Application.Resources 中的 ControlTemplate?
剩下的问题是如何绑定到“ControlTemplate”中的附加属性?
我已经尝试了几种方法,例如
Text="{Binding Path=(Attached:TextBoxProperties.Label),
Source={x:Static Attached:TextBoxProperties}, FallbackValue=''}"
但包含附加属性的TextBoxProperties 类不是静态的。
更新>>>
感谢 H.B.我发现我可以使用以下代码访问ControlTemplate。
ControlTemplate labelControlTemplate =
(ControlTemplate)Application.Current.FindResource("LabelTextBoxTemplate");
【问题讨论】:
标签: wpf data-binding resources controltemplate attached-properties