我有以下按钮样式:
<Style TargetType="Button"
BasedOn="{StaticResource {x:Type Control}}">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border CornerRadius="4" Background="{TemplateBinding Background}">
<Grid>
<Path Data="{TemplateBinding Content}" Fill="White" />
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
有一个Converter可将一些枚举值转换为所需的路径数据字符串:
public class SugarOperationEnumToSolidImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var sugarOperationEnum = (SugarOperationEnum)value;
switch (sugarOperationEnum)
{
case SugarOperationEnum.Increment:
return CoffeeMachineIcons.PlusIcon;
case SugarOperationEnum.Decrement:
return CoffeeMachineIcons.MinusIcon;
}
throw new NotImplementedException();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
和一个按钮:
<Button Style="{StaticResource SugarButtonStyle}"
Content="{Binding DecrementSugarButtonContent, Converter={StaticResource SugarOperationEnumToSolidImageConverter}}"/>
由于某种原因,当我将其绑定到路径数据中时,按钮内容的TemplateBinding无法正常工作。
任何想法我该如何克服?
答案 0 :(得分:1)
您应该使用Geometry.Parse绑定数据,因为数据是几何而不是字符串,所以您可以像这样修改转换器:
public class SugarOperationEnumToSolidImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var sugarOperationEnum = (SugarOperationEnum)value;
switch (sugarOperationEnum)
{
case SugarOperationEnum.Increment:
return Geometry.Parse(CoffeeMachineIcons.PlusIcon);
case SugarOperationEnum.Decrement:
return Geometry.Parse(CoffeeMachineIcons.MinusIcon);
}
throw new NotImplementedException();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
但是请考虑将路径存储为静态资源,而不是每次都对其进行解析。