今天在Nerd Plus Art博客上,有一篇关于为箭头创建 WPF 资源的帖子,作者经常使用该资源。我有一个带有后退和前进按钮的辅助项目,所以我认为左箭头和右箭头在这些按钮上会很好用。
我将LeftArrow
和RightArrow
Geometries 添加到我的应用程序资源中,然后将它们用作按钮的内容:
<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
从 abool
到 a 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();
}
}
(我意识到我可能应该使用系统颜色而不是硬编码的黑色和灰色,但我只是想让这个工作,首先。)
我修改了 的Fill
属性Path
以使用我的转换器(我在应用程序的资源中创建):
<Path Data="{StaticResource LeftArrow}" Width="10" Height="8"
Stretch="Fill"
Fill="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Button}, Path=IsEnabled, Converter={StaticResource EnabledColorConverter}}"/>
不幸的是,这不起作用,我不知道为什么。当我运行它时,根本没有绘制箭头。我在 Visual Studio 中检查了输出窗口,没有显示绑定错误。bool
我还根据是否应启用按钮验证了转换器中的值是否正确。
如果我将Path
背面更改为 a (并以与 相同的方式TextBlock
绑定其属性),则文本始终以黑色绘制。Foreground
Path.Fill
难道我做错了什么?为什么Brush
我的转换器返回的不用于Path
在按钮中呈现?