在WPF中格式化CommandParameter字符串
我希望CommandParameter是“9”,而不是“9”在WPF中格式化CommandParameter字符串,wpf,visual-studio,xaml,Wpf,Visual Studio,Xaml,我希望CommandParameter是“9”,而不是“9” 我知道我可以只做CommandParameter=“9”,但我想拿出一个样式来应用于多个按钮。我尝试过使用StringFormat=但似乎无法使其工作。有没有一种方法可以在不使用代码隐藏的情况下执行此操作?如果您可以修改NumberPress引用的命令,那么最简单的解决方案就是解析那里的命令参数以获取数字。如果这不是一个选项,那么另一个解决方案是创建一个IValueConverter类并将其添加到CommandParameter绑
我知道我可以只做CommandParameter=“9”,但我想拿出一个样式来应用于多个按钮。我尝试过使用StringFormat=但似乎无法使其工作。有没有一种方法可以在不使用代码隐藏的情况下执行此操作?如果您可以修改NumberPress引用的命令,那么最简单的解决方案就是解析那里的命令参数以获取数字。如果这不是一个选项,那么另一个解决方案是创建一个IValueConverter类并将其添加到CommandParameter绑定中
<Button Content="_9"
Focusable="False"
Command="{Binding NumberPress}"
CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self},
Path=Content, Converter={StaticResource NumberConverter}}"
Margin="92,134,92,129" />
如果您在评论中提到的“u”严格地说只是视图的一部分,那么您确实可以使用Format属性将其显示在内容
和ContentStringFormat
中
比如说:
<Button Margin="92,134,92,129"
Command="{Binding NumberPress}"
CommandParameter="{Binding Content,
RelativeSource={RelativeSource Self}}"
Content="9"
ContentStringFormat="_{0}"
Focusable="False"
Style="{DynamicResource NumberButton}" />
这样,如果您将按钮的
内容
绑定到一个值,您就不必一直在那里预加“”了。这有点可怕,但您可以只绑定到标记
,然后将标记
设置为9,并将按钮内容保留为9-不知道stringformat是否适用于命令参数(您可能认为它会…)我可能没有正确使用StringFormat,您能告诉我在这种情况下该如何操作吗?
public class NumberConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is string)
{
string strVal = ((string)value).TrimStart('_');
int intVal;
if (int.TryParse(strVal, out intVal))
return intVal;
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value;
}
}
<Button Margin="92,134,92,129"
Command="{Binding NumberPress}"
CommandParameter="{Binding Content,
RelativeSource={RelativeSource Self}}"
Content="9"
ContentStringFormat="_{0}"
Focusable="False"
Style="{DynamicResource NumberButton}" />