c# - WPF 数据绑定(bind)和 IValueConverter

标签 c# wpf data-binding converter

为什么当我在 WPF 中的绑定(bind)表达式中使用转换器时,当数据更新时值没有更新。

我有一个简单的 Person 数据模型:

class Person : INotifyPropertyChanged
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

我的绑定(bind)表达式如下所示:

<TextBlock Text="{Binding Converter={StaticResource personNameConverter}" />

我的转换器看起来像这样:

class PersonNameConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Person p = value as Person;
        return p.FirstName + " " + p.LastName;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

如果我在没有转换器的情况下绑定(bind)数据,效果会很好:

<TextBlock Text="{Binding Path=FirstName}" />
<TextBlock Text="{Binding Path=LastName}" />

我错过了什么?

编辑: 只是为了澄清一些事情,关于需要实现的 INotifyPropertyChanged 接口(interface),Joel 和 Alan 都是正确的。实际上我确实实现了它,但它仍然不起作用。

我不能使用多个 TextBlock 元素,因为我试图将窗口标题绑定(bind)到全名,而窗口标题不采用模板。

最后,添加复合属性“FullName”并绑定(bind)到它是一个选项,但我仍然想知道为什么当绑定(bind)使用转换器时不会发生更新。即使我在转换器代码中放置一个断点,当对基础数据完成更新时,调试器也不会到达那里:-(

谢谢, 乌里

最佳答案

您还可以使用 MultiBinding.. 绑定(bind)到 Person 对象、FirstName 和 LastName。这样,一旦 FirstName 或 LastName 引发属性更改事件,该值就会更新。

<MultiBinding Converter="{IMultiValueConverter goes here..}">
    <Binding />
    <Binding Path="FirstName" />
    <Binding Path="LastName" />
</MultiBinding>

或者,如果您只使用 FirstName 和 LastName,则将 Person 对象从绑定(bind)中剥离为如下所示:

<MultiBinding Converter="{IMultiValueConverter goes here..}">
    <Binding Path="FirstName" />
    <Binding Path="LastName" />
</MultiBinding>

MultiValueConverter 看起来像这样:

class PersonNameConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
            return values[0].ToString() + " " + values[1].ToString();
    }

    public object ConvertBack(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
            throw new NotImplementedException();
    }
}

当然,选择的答案也有效,但 MultiBinding 的工作更优雅......

关于c# - WPF 数据绑定(bind)和 IValueConverter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/174841/

相关文章:

c# - WPF 嵌套数据绑定(bind)到控件 - 为什么它不起作用

c# - 创建自定义 DataGrid 的 ItemsSource

c# - 根据背景使前景颜色为黑色或白色

c# - StackPanel 中的 TextWrap

wpf - Silverlight 的 ScrollViewer.ScrollIntoView 的 WPF 等效项是什么?

c# - 如何使用来自单独的 xaml 文件的样式

wpf - 当项目添加到列表框时动画 WPF 数据模板?

C# Excel 左右边框

c# - 有没有办法在 C# 中通过引用对对象进行一致的排序/排序?

c# - 从 .NET 中的数据库中提取 varbinary 会导致 IndexOutOfRangeException