1

私はグリッドビューを持っています:

      <GridView xmlns:controls="using:Windows.UI.Xaml.Controls">
        <GridView.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Image Source="{Binding Image}"></Image>
                    <Grid Height="50" Width="50" Background="{Binding Color}"></Grid>
                    <TextBlock FontSize="25" TextWrapping="Wrap" Text="{Binding Name}" Margin="10,10,0,0"/>
                </Grid>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>

これはobservablecollectionにバインドされています:

   ObservableCollection<KeyItem> Keys = new ObservableCollection<KeyItem>();

   Keys.Add(new KeyItem { Name = "jfkdjkfd" });
   Keys.Add(new KeyItem { Name = "jfkdjkfd" });

   myView.ItemsSource = Keys;

キーアイテムはこれです:

public class KeyItem
{
    public string Name { get; set; }
    public ImageSource Image { get; private set; }
    public Brush Color
    {
        get;
        set;
    }
}

これは、itemssourceに割り当てる前に色を設定すると正常に機能します。

ただし、KeyItemが割り当てられた後、プログラムでColorプロパティを変更し、Bindingで色を変更できるようにする必要もあります。しかし、この構成では、これは機能していません。

これを機能させるための最良のアプローチは何でしょうか?

4

1 に答える 1

5

クラスはを実装する必要がありますINotifyPropertyChanged。これにより、バインディングはいつ更新するかを知ることができます。監視可能なコレクションがあると、通知を受け取るためにコレクションへのバインディングのみが通知されます。コレクション内の各オブジェクトもINotifyPropertyChanged実装されている必要があります。

[CallerMemberName]inの使用に注意してくださいNotifyPropertyChanged。これにより、デフォルト値を持つオプションのパラメーターが、呼び出し元のメンバーの名前をその値として使用できるようになります。

public class KeyItem : INotifyPropertyChanged
{
    private string name;
    public string Name 
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
            NotifyPropertyChanged();
        }
    }

    private ImageSource image;
    public ImageSource Image 
    {
        get
        {
            return image;
        }
        set
        {
            image = value;
            NotifyPropertyChanged();
        }
    }

    private Brush color;
    public Brush Color
    {
        get
        {
            return color;
        }
        set
        {
            color = value;
            NotifyPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    // This method is called by the Set accessor of each property. 
    // The CallerMemberName attribute that is applied to the optional propertyName 
    // parameter causes the property name of the caller to be substituted as an argument. 
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
于 2012-12-15T23:18:26.870 に答える