要增加值,请使用实现IValueConverter 的类,如下所述:
http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx
实质上,实现IValueConverter 的类将在名为Convert 的方法中拦截value。您从此方法返回的值是您真正想要显示的值。考虑:
命名空间 Sharp {
public class MyConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
// First cast the value to an 'int'.
Int32 theInputtedValue = (Int32)value;
// Then return the newly formatted string.
return String.Format("{0}% Completed", theInputtedValue);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
throw new NotImplementedException();
}
}
}
请注意,在上面的示例中,值转换器位于命名空间 Sharp 中。现在我们将其添加到 XAML 定义中:
<Window x:Class="Sharp.MyWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:lol="clr-namespace:Sharp">
最后一行是我们的值转换器所在的命名空间(也就是说,lol 现在将指向 Sharp CLR 命名空间。
接下来我们将这个类添加到我们的Window 资源中:
<Window.Resources>
<lol:MyConverter x:Key="TheValueConverter" />
</Window.Resources>
这会创建一个可以在 XAML 中使用的类的实例。所以,到目前为止,我们的 XAML 看起来像这样:
<Window x:Class="Sharp.MyWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:lol="clr-namespace:Sharp">
<Window.Resources>
<lol:MyConverter x:Key="TheValueConverter" />
</Window.Resources>
现在我们只需将其添加到您的内容演示器中,如下所示:
<ContentPresenter Content="{TemplateBinding Value, Converter={StaticResource TheValueConverter}}" ... />
这告诉ContentPresenter,当它呈现值时,它应该使用TheValueConverter 实例,它是我们ValueConverter 的一个实例。需要注意两点:(1) 确保使用instance 的名称 (TheValueConverter) 而不是 class 的定义 (MyConverter)。 (2) 确保将实例名称包裹在{StaticResource}中。