MVVM更新列表框项目backcolor使用按钮命令

时间:2017-11-12 09:41:44

标签: c# wpf mvvm

我尝试使用以下命令独立更新列表框项目背景: 模型

public class Item
{
    public Item()
    {
        this.BackColor = new SolidColorBrush(Colors.WhiteSmoke);
    }

    public int Number { get; set; }
    public int Duration { get; set; }
    public string Name { get { return Number.ToString(); } }
    public SolidColorBrush BackColor { get; set; }
}

视图模型

private ObservableCollection<Item> _items;

public ObservableCollection<Item> Items
{
    get { return _items; }
    set { OnPropertyChange(ref _items, value); }
}

按钮命令

public ICommand StartCommand { get; set; }

public void start()
{
    foreach (var item in Items
    {
        item.BackColor = new SolidColorBrush(Colors.LightGreen);
        // Do some work .....
    }
}

CTOR

public MainViewModel()
{
    StartCommand = new RelayCommand(start);
    LoadItems();
}

的Xaml

<ListBox  ItemsSource="{Binding Items}" >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Border 
                Height="50" 
                BorderThickness="1" 
                BorderBrush="Silver" 
                CornerRadius="5" 
                Margin="10,10,10,5" 
                Background="{Binding BackColor,
                UpdateSourceTrigger=PropertyChanged}">
            </Border>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

我可以更新可观察的收藏数据,删除项目但不能更改项目背景。请帮忙。

&#34;更新&#34; :你可以看到我不想改变整个列表框的颜色,所以我不能绑定像#34; ItemBackground&#34;这样的公共属性。相反,我必须绑定到集合对象属性&#34; BackColor&#34;

1 个答案:

答案 0 :(得分:0)

就像@pix在链接帖子中建议的那样,你错过了Item Class中的INotifyPropertyChanged接口实现。如果没有INotifyPropertyChanged,您的UI将无法获得您所做更改的更新。

public class Item : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

您的BackColor属性必须使用OnPropertyChanged:

private SolidColorBrush backColor;

public SolidColorBrush BackColor
{
    get { return backColor; }
    set
    {
        backColor = value;
        OnPropertyChanged(nameof(BackColor));
    }
}