如何在绑定列表数据发生变化时通知XAML属性?

时间:2013-12-11 09:25:35

标签: c# wpf binding

我正在使用以下代码进行绑定

XAML

<StackPanel x:Name="channelsRecordTimeData" Orientation="Vertical">
    <ItemsControl x:Name="channelRecordTimeItems" ItemsSource="{Binding}">
        <ItemsControl.ItemTemplate> 
            <DataTemplate>
                <Grid x:Name="gridChannelRecordTimeItem" Width="{Binding Path=ChannelRecordTimeItemWidth}"                                                                                                                
                      Height="{Binding Path=ChannelRecordTimeItemHeight}" Margin="{Binding Path=ChannelRecordTimeItemsMargin}"
                        HorizontalAlignment="Left" DataContext="{Binding Path=ListRecordTime}">
                    <Grid.Background>
                        <ImageBrush x:Name="gridChannelRecordTimeItemBgr" ImageSource="..\Resources\playback_grid_channel_record_time_item_bgr_normal.png"/>
                    </Grid.Background>                                    
                </Grid>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</StackPanel>

C#

public class DATA
{
    public double ChannelRecordTimeItemWidth { set; get; }
    public double ChannelRecordTimeItemHeight { set; get; }
    public Thickness ChannelRecordTimeItemsMargin { set; get; }
    public List<RecordTime> ListRecordTime { set; get; }

    public DATA()
    {
        ChannelRecordTimeItemWidth = 1000;
        ChannelRecordTimeItemHeight = 20;
        ChannelRecordTimeItemsMargin = new System.Windows.Thickness(0, 0, 0, 0);
        ListRecordTime = null;
    }
}

public static List<DATA> listDATA = new List<DATA>();
for(int i = 0 ; i < 10 ; i++)
{
    DATA data = new DATA();
    listDATA.Add(data);
}
channelRecordTimeItems.ItemsSource = listDATA;
channelRecordTimeItems.Items.Refresh();

当我使用代码行

时,此代码将通知XAML更新
listDATA[0].ChannelRecordTimeItemWidth -= 15;

当我们将listDATA操作为

时,有任何方法可以自动更新XAML属性
listDATA.RemoveAt();
listDATA.Add();
listDATA.Clear();

不调用以下两行代码

channelRecordTimeItems.ItemsSource = listDATA;
channelRecordTimeItems.Items.Refresh();

1 个答案:

答案 0 :(得分:1)

仅在underlying source collection is implementing INotifyCollectionChanged引发CollectionChanged事件以更新GUI组件的情况下更新GUI。

您可以使用ObservableCollection在内部为您提供此功能。

替换

public static List<DATA> listDATA = new List<DATA>();

public static ObservableCollection<DATA> listDATA = new ObservableCollection<DATA>();