Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

WPF when I change the string to which binded Text of TextBlock, the text doesn't change

I have an ItemTemplate in ListBox which have Image(Flag of Country) and TextBlock(Name of Country)

ListBox:

<ListBox x:Name="countriesList" Background="#a79473" Foreground="#e6d9c4">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" Height="40" Background="#a79473">
                <Image Source="{Binding Flag.Source}"/>
                <TextBlock Text="{Binding Name}" Foreground="#e6d9c4" FontSize="20"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Country class:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class Country
{
    public string Name { get; set; }
    public Image Flag { get; set; }
    
    public Country()
    {
        Flag = new Image();
    }
}

when the Country changes the Flag, everything works correctly, but when the Name changes nothing happens,
I guess when I change the Name, the binding is still binded to old Name, but what to do with it?

Country country = new Country();
countriesList.Items.Add(country);
country.Name = "test";
country.Flag.Source = flagImage.Source;

P.S. this is my first question on stackoverflow and I hope I made no mistakes anywhere 🙂

>Solution :

Your Country class should implement INotifyPropertyChanged and raise the PropertyChanged event for the Name property whenever it ‘s set to a new value:

public class Country : INotifyPropertyChanged
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set { _name = value; RaisePropertyChanged(); }
    }

    public Image Flag { get; set; }

    public Country()
    {
        Flag = new Image();
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void RaisePropertyChanged([CallerMemberName]string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

The reason why setting the Source property works as-is is because it’s a dependency property. As a side note, a model like Country shouldn’t contain UI elements like Image.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading