简体   繁体   中英

Converter on a get-only property is not called (WPF)

I have the following this XAML:

<ListBox Background="{Binding CurrentJob, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource JobToColorConverter}, Mode=TwoWay}">

And I'd like to change my ListBox background depending on the CurrentJob property. Here is a part of my code behind:

private Job CurrentJob => ((FooClass) WindowsPanel.Children[0]).CurrentJob;

And here is my (dummy) converter:

public class JobToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var j = (Job) value;
        return new SolidColorBrush(Color.FromArgb(100, 60, 116, 154))
    } 

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

I verified that the

Now, my problem is that when CurrentJob change, no converter event is fired, and my Convert method is never called.

I think this is because CurrentJob is a read-only property, and so the WPF framwork does not know when the property change. It is correct?

private Job CurrentJob; need to fire the PropertyChanged event. Inherit your class from INotifyPropertyChanged interface and implement it in that way:

public event PropertyChangedEventHandler PropertyChanged;

protected void OnPropertyChanged(string name)
{
    PropertyChangedEventHandler handler = PropertyChanged;

    if (handler != null)
    {
        handler( this, new PropertyChangedEventArgs(name) );
    }
}


private Job currentJob;

public Job CurrentJob
{
    get { return curentJob; }
    private set
    {
        if (this.currentJob != value)
        {
            this.currentJob = value;
            OnPropertyChanged("CurrentJob");
        }
    }
}

Your property is private, try making it public.

Also, given that the property is read-only and doesn't propagate changes from ((FooClass) WindowsPanel.Children[0]).CurrentJob you could make the binding OneTime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM