绑定背景颜色的WPF不会更新

时间:2016-06-25 02:51:08

标签: c# wpf xaml data-binding

我在Appointments系统上工作,我有一个包含DataTemplate的Listbox有一个切换按钮代表每个约会,如果约会确认背景颜色应该改变,这是我的ListBox:

<ListBox>                       
        <ListBox.ItemTemplate>
            <DataTemplate>
                <ToggleButton Background="{Binding Converter={StaticResource AppointmentStatusColor}, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged}" IsChecked="{Binding IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}, Mode=FindAncestor}}">
                    <StackPanel Orientation="Horizontal" Width="370">
                        <TextBlock Text="{Binding AppointmentID}"/>
                        <TextBlock Text="{Binding Patient.FullName}"/>
                    </StackPanel>
                </ToggleButton>
            </DataTemplate>
        </ListBox.ItemTemplate>
</ListBox>

Background属性绑定到IValueConverter:

public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        Brush _appointmentStatusBrush = null;
        var fc = new BrushConverter();
        if (value == null)
            return null;
        Appointment _appointment = (Appointment)value;
        switch (_appointment.Status)
        {
            case 0:
                _appointmentStatusBrush = (Brush)fc.ConvertFrom("#FFFBF7CC");
                break;
            case 1:
                _appointmentStatusBrush = (Brush)fc.ConvertFrom("#FFFFFFFF");
                break;
        }
        return _appointmentStatusBrush;
    }

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

添加新约会时绑定有效,但当我更新现有约会状态并刷新列表时,颜色不会更新!!

提前致谢

1 个答案:

答案 0 :(得分:-1)

Background属性应与Appointment.Status绑定到Mode=TwoWay属性。

然后,当Status更改时,将调用Converter

因此,您的绑定应如下所示:Background="{Binding Status, Converter={StaticResource AppointmentStatusColor}, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged}"