2017-10-15 69 views
1

在我得到重复问题之前,我只想说我似乎无法找到解决我的问题的方法。我想要做的就是将一个数组的元素绑定到一个属性,并且似乎无法弄清楚我是如何因为缺乏经验。将Array的元素绑定到xaml属性

这里是我的C#代码的样子:

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; 
} 

下面是我的XAML属性如下:

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

我的代码的执行没有任何错误去关闭但实际上并没有绑定任何东西。但是,如果我使用BitmapImage变量而不是数组中的元素,它工作得很好。

+0

你是如何设置WeatherIconSource属性?因为如果你单独修改每个索引(即'WeatherIconSource [0] = myBitmap;'),那么你将不会通知UI的属性更改。如果您只是简单地使用'ObservableCollection ',您将节省很多痛苦。数组不会将更改传达给UI。 – Laith

+0

我可以说我有一系列能够获得正确财产的方法吗?其他一些属性也会共享这些方法中的一部分。为了更新UI,我设置了一个计时器来调用更新这些数组的方法。每当它更新数组时,都会有一个调用PropertyChanged来更新UI的'set'。当我不使用数组并为每个属性提供一个唯一的路径时,此功能完美无瑕。但是,如果我使用数组,它会使我的代码看起来更好,并节省数百行代码。编辑:我应该添加我在不同的线程上运行的一天中的某些时间更新UI。 – Oybek

+0

好吧,我的回答如下:) – Laith

回答

1

数组不是可绑定到UI,至少不是每个索引。你需要使用一个ObservableCollection<T>

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

不要打扰使用数组;如果你坚持使用数组,你无法通知的单指标属性更改

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

,那么你必须告知物业不管你什么时候更新一个索引整个集合改变:

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

但如果你这样做,你会强制刷新所有索引。您的所有图像都将重绘。如果您的应用程序对于小图像很简单,您可能会忽略这一点;否则,请更改为ObservableCollection<T>

如果你硬编码绑定与一个确切的指标,如:

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

然后实例化您的收藏这样的,所以你没有得到一个IndexOutOfRangeException

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

这是一个很漂亮的解决方案。它完美的作品。非常感谢你! – Oybek

0

它应该是,

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

我应该补充一点,我已经尝试过,但有相同的结果。 – Oybek

+0

以上在我的解决方案中正常工作 – Sajeetharan

+0

我刚刚尝试了一次,并且我立即纠正。我的NotifyPropertyChanged方法可能有问题吗? – Oybek