在今天的博客Nerd Plus Art上,有一篇关于创建箭头的WPF资源的文章,作者经常使用它。我有一个具有后退和前进按钮的项目,所以我认为左右箭头在这些按钮上效果很好。为笔刷创建一个WPF ValueConverter
我加入了LeftArrow
和RightArrow
几何形状,以我的应用程序的资源,然后把他们当作按钮的内容:
<Application x:Class="Notes.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="Views/MainWindow.xaml">
<Application.Resources>
<Geometry x:Key="RightArrow">M0,0 L1,0.5 0,1Z</Geometry>
<Geometry x:Key="LeftArrow">M0,0.5 L1,1 1,0Z</Geometry>
</Application.Resources>
</Application>
<Button x:Name="BackButton"
Padding="5,5,5,5"
Command="{x:Static n:Commands.GoBackCommand}">
<Path Data="{StaticResource LeftArrow}" Width="10" Height="8"
Stretch="Fill" Fill="Black"/>
</Button>
<Button x:Name="ForwardButton"
Padding="5,5,5,5"
Command="{x:Static n:Commands.GoForwardCommand}">
<Path Data="{StaticResource RightArrow}" Width="10" Height="8"
Stretch="Fill" Fill="Red" />
</Button>
这工作,除了箭头黑色绘制无论按钮已启用或未启用。所以,我创建了一个ValueConverter
从去一个bool
到Brush
:
class EnabledColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
CultureInfo culture)
{
bool b = (bool)value;
return b ? Brushes.Black : Brushes.Gray;
}
public object ConvertBack(object value, Type targetType, object parameter,
CultureInfo culture)
{
throw new NotImplementedException();
}
}
(我知道我应该使用,而不是系统颜色硬编码的黑色和灰色,但我只想得到这个工作,首先。)
我修改了Path
的Fill
财产使用我的转换器(这是我的应用程序的资源范围内创建):
<Path Data="{StaticResource LeftArrow}" Width="10" Height="8"
Stretch="Fill"
Fill="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Button}, Path=IsEnabled, Converter={StaticResource EnabledColorConverter}}"/>
不幸的是,这并不W¯¯ ork,我不知道为什么。当我运行它时,箭头根本没有绘制。我在Visual Studio中检查了输出窗口,并没有显示任何绑定错误。我还验证了bool
是转换器中的正确值,取决于是否启用按钮。
如果我改变Path
回TextBlock
(及其Foreground
属性绑定在相同的方式为Path.Fill
),文本总是以黑色绘制。
我做错了什么?为什么我的转换器返回的Brush
未用于渲染按钮中的Path
?
不知道为什么你的代码是不工作的,但我会用样式触发这个...... – Will 2009-06-04 12:04:23