Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XAML data binding - UI not automatically updating

Tags:

c#

.net

wpf

xaml

I've made a program which stores any number of objects of my type Project. Each Project then contains any number of Files, which is another object I created for this program.

The problem I am having arises in XAML, in 2 areas, but which I imagine have a similar origin.

I have a Window which contains a ListView, populated with the Files in a selected Project. From here I can check a box beside each to turn them on or off, and if I select a file, information about it appears in the status bar of this Window.

If I turn a File off, its text colour is supposed to appear light grey in the ListView, but it does not do this automatically; I have to close the Window and re-open it. The File implements INotifyPropertyChanged, and fires this event if the on/off state changes.

I use this XAML code, where the converter is in my code behind class:

<ListBox.ItemContainerStyle>
     <Style TargetType="ListBoxItem">
          <Setter  Property="Foreground" Value="{Binding Path=IsVisible, Converter={StaticResource VisibleStateToFontColourConverter}}"/>
     </Style>
</ListBox.ItemContainerStyle>  

Also for the selected File, if the information in the file changes while it is selected (which other classes can cause to happen), I want the status bar to update automatically to reflect this change, but it doesn't; I have to click something else and then re-select the File of interest. I implement and use INotifyPropertyChanged for this too, and so I don't know why it doesn't automatically update. My XAML code for the status item is like this:

<StatusBarItem Name="statusItem_FileInfo" Content="{Binding ElementName=loadedFiles_ListView, Path=SelectedItem, Converter={StaticResource GIS_FileToInfoConverter}}"/>

Does anyone know what I'm missing that will bring it all together?

like image 913
Greg Avatar asked Feb 20 '23 09:02

Greg


1 Answers

Try to add UpdateSourceTrigger=PropertyChanged to your binding:

Value = "{Binding ... , UpdateSourceTrigger=PropertyChanged}"

Call OnPropertyChanged directly after you changed the property with the name of the changed property:

public event PropertyChangedEventHandler PropertyChanged;

private void OnPropertyChanged(string propertyName)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler == null) return;
    handler (this, new PropertyChangedEventArgs(propertyName));
}

If you change "IsVisible" call OnPropertyChanged("IsVisible")

like image 62
webber2k6 Avatar answered Feb 28 '23 03:02

webber2k6