【问题标题】:WPF TargetNullValue for Dictonary Binding not working用于字典绑定的 WPF TargetNullValue 不起作用
【发布时间】:2018-10-13 09:15:08
【问题描述】:

我有一个字典(字符串,字符串)可能没有特定键的条目。

在 XAML 中,我想通过以下行来涵盖这种情况:

<Image Source="{Binding MyDictonary[myKey], UpdateSourceTrigger=PropertyChanged, Converter={StaticResource uriToImageConverter}, TargetNullValue={StaticResource myStaticImage} }"/>

如果我不绑定到字典但在我的视图模型中有一个字符串 Nothing,则代码可以正常工作。

我还检查了它是否是转换器保险库,但如果没有有效字符串,则永远不会调用转换器。

提前感谢您对我在这里遗漏的内容的帮助/解释。

【问题讨论】:

  • 除了答案之外,您可能还会发现FallbackValue 设置很有用,如果由于某种原因绑定失败,将使用该设置。
  • @ShahinDohan 如果您将其作为答案并参考 Yanting 的解释,我会将其作为公认的答案。谢谢!
  • YantingChen 有正确的答案,TargetNullValue 对您不起作用的原因是因为您的Binding MyDictonary[myKey] 由于 KeyNotFoundException 而失败,这也是 FallbackValue 起作用的原因:)
  • 在 Visual Studio 的“输出窗口”中搜索“System.Windows.Data Error”。它将帮助您找到绑定错误。

标签: .net wpf vb.net


【解决方案1】:

您需要为“myKey”添加一个没有任何内容的字典条目 (MyDictonary.Add(“myKey”, Nothing)) 以便它可以获取“Nothing”值而不会导致异常。

实现此目的的另一种方法是在 ViewModel 上添加一个额外的“DictionaryValue”属性。

<StackPanel>
    <TextBox Text="{Binding DictionaryKey, UpdateSourceTrigger=PropertyChanged}"/>
    <Image Source="{Binding DictionaryValue, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource uriToImageConverter}, TargetNullValue={StaticResource myStaticImage} }"/>
</StackPanel>


Public Class ViewModel
    Inherits INotifyPropertyChanged

    Public Sub New()
        MyDictonary = New Dictionary(Of String, String)()
    End Sub

    Private _key As String

    Public Property DictionaryKey As String
        Get
            Return _key
        End Get
        Set(ByVal value As String)

            If _key <> value Then
                _key = value
                RaisePropertyChanged(NameOf(DictionaryKey))
                RaisePropertyChanged(NameOf(DictionaryValue))
            End If
        End Set
    End Property

    Public ReadOnly Property DictionaryValue As String
        Get

            If DictionaryKey IsNot Nothing AndAlso MyDictonary.Keys.Contains(DictionaryKey) Then
                Return MyDictonary(DictionaryKey)
            Else
                Return Nothing
            End If
        End Get
    End Property

    Public Property MyDictonary As Dictionary(Of String, String)
    Public Event PropertyChanged As PropertyChangedEventHandler

    Private Sub RaisePropertyChanged(ByVal propertyName As String)
        PropertyChanged?.Invoke(Me, New PropertyChangedEventArgs(propertyName))
    End Sub
End Class

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多