深入探索Silverlight数据绑定与模板技术
立即解锁
发布时间: 2025-08-13 03:16:10 阅读量: 19 订阅数: 36 

### 深入探索Silverlight数据绑定与模板技术
#### 一、Silverlight数据绑定基础
Silverlight的数据绑定系统为开发者提供了强大的功能,但与WPF不同,它缺少`IMultiValueConverter`接口,这意味着开发者只能进行单个值的转换,无法进行值的组合或计算。
#### 二、使用值转换器创建对象
值转换器在弥合数据存储方式和显示方式之间的差距时非常重要。例如,当数据库中的图片数据以字节数组形式存储时,可以使用值转换器将其转换为`BitmapImage`对象。
以下是一个`ImagePathConverter`的示例:
```vb
Public Class ImagePathConverter
Implements IValueConverter
Private _rootUri As String
Public Property RootUri() As String
Get
Return _rootUri
End Get
Set(ByVal value As String)
_rootUri = value
End Set
End Property
Public Sub New()
Dim uri As String = HtmlPage.Document.DocumentUri.ToString()
' Remove the web page from the current URI to get the root URI.
RootUri = uri.Remove(uri.LastIndexOf("/"c), _
uri.Length - uri.LastIndexOf("/"c))
End Sub
Public Function Convert(ByVal value As Object, ByVal targetType As Type, _
ByVal parameter As Object, ByVal culture As CultureInfo) As Object _
Implements IValueConverter.Convert
Dim imagePath As String = RootUri & "/" & CStr(value)
Return New BitmapImage(New Uri(imagePath))
End Function
Public Function ConvertBack(ByVal value As Object, ByVal targetType As Type, _
ByVal parameter As Object, ByVal culture As CultureInfo) As Object _
Implements IValueConverter.ConvertBack
' Images aren't editable, so there's no need to support ConvertBack.
Throw New NotSupportedException()
End Function
End Class
```
使用步骤如下:
1. 将转换器添加到资源中:
```xml
<UserControl.Resources>
<local:ImagePathConverter x:Key="ImagePathConverter"></local:ImagePathConverter>
</UserControl.Resources>
```
2. 创建绑定表达式:
```xml
<Image Margin="5" Grid.Row="2" Grid.Column="1" Stretch="None"
HorizontalAlignment="Left" Source=
"{Binding ProductImagePath, Converter={StaticResource ImagePathConverter}}">
</Image>
```
为了提高这个示例的健壮性,可以添加一些属性来处理异常情况,例如添加`SuppressExceptions`属性或`DefaultImage`属性。
#### 三、应用条件格式
有些值转换器用于根据数据规则格式化元素的外观。例如,`PriceToBackgroundConverter`可以根据产品价格设置不同的背景颜色。
以下是`PriceToBackgroundConverter`的示例:
```vb
Public Class PriceToBackgroundConverter
Implements IValueConverter
Private _minimumPriceToHighlight As Double
Public Property MinimumPriceToHighlight() As Double
Get
Return _minimumPriceToHighlight
End Get
Set(ByVal value As Double)
_minimumPriceToHighlight = value
End Set
End Property
Private _highlightBrush As Brush
Public Property HighlightBrush() As Brush
Get
Return _highlightBrush
End Get
Set(ByVal value As Brush)
_highlightBrush = value
End Set
End Property
Private _defaultBrush As Brush
Public Property DefaultBrush() As Brush
Get
Return _defaultBrush
End Get
Set(ByVal value As Brush)
_defaultBrush = value
End Set
End Property
Public Function Convert(ByVal value As Object, ByVal targetType As
```
0
0
复制全文
相关推荐










