0

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:

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 :)

1 Answers1

0

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.

mm8
  • 163,881
  • 10
  • 57
  • 88