我已经基于ListBox
编写了一个自定义控件。它包含默认的ItemTemplate
,该图像显示通过自定义依赖项属性提供给ListBox
的图像。该控件还包含一个默认图像,当用户不将图像提供给dependency属性时,将使用该图像。
到目前为止,此方法仍然有效,但是现在我发现了一个小问题,我不知道如何解决。
当我在XAML设计器中使用自定义控件时,它首先显示默认图像。当我将图像的依赖属性设置为其他图像时,新图像将立即显示在XAML设计器中。]
但是当我再次删除新图像的XAML属性时,XAML设计器仅显示白色矩形而不是默认图像。
我认为是因为将图像的依赖项属性设置为某个值,然后将其删除,所以我将该值置为零。但是,即使当我在CoerceCallback
中检查null并在强制值为null时还给默认图像时,也不起作用。
为依赖项属性支持回退值的最佳方法是什么?
TestControl.vb
Public Class TestControl Inherits ListBox Private Shared _defaultResources As ResourceDictionary Shared Sub New() _defaultResources = New ResourceDictionary _defaultResources.Source = New Uri("...") End Sub Public Shared ReadOnly TestProperty As DependencyProperty = DependencyProperty.Register(NameOf(TestControl.Test), GetType(ImageSource), GetType(TestControl), New FrameworkPropertyMetadata(Nothing, AddressOf TestControl.OnTestChanged, AddressOf TestControl.OnTestCoerce)) Public Property Test As ImageSource Get Return DirectCast(MyBase.GetValue(TestControl.TestProperty), ImageSource) End Get Set(value As ImageSource) MyBase.SetValue(TestControl.TestProperty, value) End Set End Property Private Shared Sub OnTestChanged(d As DependencyObject, e As DependencyPropertyChangedEventArgs) End Sub Private Shared Function OnTestCoerce(d As DependencyObject, value As Object) As Object If (value Is Nothing) Then Return TryCast(_defaultResources.Item("TestImage"), ImageSource) End If Return value End Function Public Sub New() Me.Test = TryCast(_defaultResources.Item("TestImage"), ImageSource) End Sub End Class
当我像这样使用该控件时
。当我将XAML更改为<local:TestControl ItemsSource="{Binding Items}" />
每个项目都显示默认图像在设计时
。但是,当我再次删除<local:TestControl ItemsSource="{Binding Items}" Test="{StaticResource NewImage}" />
每个项目都显示新项目在设计时
Test="{StaticResource NewImage}"
时,它不会返回到默认图像。我已经基于ListBox编写了一个自定义控件。它包含一个默认的ItemTemplate,该模板显示由自定义依赖项属性提供给ListBox的图像。该控件还包含一个默认的...
[确定,经过一些测试(使用this technique),我发现了问题的根源。