Oybek
Oybek

Reputation: 123

Bind an element of Array to a xaml property

Before I get a duplicate question, I just want to say I can't seem to find a solution to my problem at all. All I want to do is bind an element of an array to a property and can't seem to figure out how because of my lack of experience.

Here is how my C# code looks:

public class MainPageImplement : INotifyPropertyChanged
{
    BitmapImage[] weatherIconSource = new BitmapImage[7];
    public BitmapImage[] WeatherIconSource
    {
        get { return weatherIconSource; }
        set
        {
            weatherIconSource = value;
            NotifyPropertyChanged("WeatherIconSource");
        }
    }
    private void NotifyPropertyChanged(string propName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

Here is how my XAML property looks:

       <Image Grid.Column="1" Name="WeatherIconZero" Source="{x:Bind PropertyName.WeatherIconSource[0], Mode=OneWay}" HorizontalAlignment="Center" VerticalAlignment="Center" />

My code executes without any errors to go off of but does not actually bind anything. However, it works just fine if I used BitmapImage variable and not an element from array.

Upvotes: 2

Views: 7068

Answers (2)

Laith
Laith

Reputation: 6091

Arrays are not bindable to the UI, at least not per index. You need to use an ObservableCollection<T>:

public ObservableCollection<BitmapImage> WeatherIconSource { get; } = new ObservableCollection<BitmapImage>();

Don't bother using arrays; you cannot notify a single-index property change

NotifyPropertyChanged("WeatherIconSource[5]"); // Doesn't work.

If you're stuck with arrays, then you have to notify property changed on the entire collection whenever you update a single index:

WeatherIconSource[5] = myNewBitmap;
NotifyPropertyChange("WeathIconSource"); // Updates all [0] [1] ... [n]

But if you do this, you will force a refresh on all indexes. All your images will redraw. You may get away with this if your app is simple with small images; otherwise, make the change to ObservableCollection<T>.

If you have hardcoded bindings with an exact index, like this:

Source="{x:Bind PropertyName.WeatherIconSource[0], Mode=OneWay}"
Source="{x:Bind PropertyName.WeatherIconSource[2], Mode=OneWay}"
Source="{x:Bind PropertyName.WeatherIconSource[5], Mode=OneWay}"

then instantiate your collection like this so you don't get an IndexOutOfRangeException:

public ObservableCollection<BitmapImage> WeatherIconSource { get; } = new ObservableCollection<BitmapImage>
{
    null, // [0]
    null, // [1]
    null,
    null,
    null,
    null,
    null  // [6]
};

Upvotes: 3

Sajeetharan
Sajeetharan

Reputation: 222522

It should be,

`<Image Grid.Column="1" Name="WeatherIconZero"  Source="{Binding weatherIconSource[0]}" HorizontalAlignment="Center" VerticalAlignment="Center" /`>

Upvotes: 0

Related Questions