今天在Nerd Plus Art博客上,有一篇关于创建WPF箭头资源的文章,作者经常使用这些资源。我有一个副业项目需要前进和后退按钮,所以我认为左右箭头在这些按钮上非常适合。
我将
那个方法可行,但不管按钮是否启用箭头都是黑色的。因此,我创建了一个ValueConverter,将bool类型转换为Brush类型:
很不幸,这并没有起作用,我不确定原因。当我运行它时,箭头根本没有被绘制。我在Visual Studio的输出窗口中检查了一下,没有显示任何绑定错误。我还验证了转换器中的
如果我将
我做错了什么吗?为什么我的转换器返回的
我将
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}}"/>
很不幸,这并没有起作用,我不确定原因。当我运行它时,箭头根本没有被绘制。我在Visual Studio的输出窗口中检查了一下,没有显示任何绑定错误。我还验证了转换器中的
bool
值是否正确,基于按钮是否应该启用。如果我将
Path
改回TextBlock
(并以与Path.Fill
相同的方式绑定其Foreground
属性),则文本始终以黑色绘制。我做错了什么吗?为什么我的转换器返回的
Brush
没有用于渲染按钮中的Path
?