2017-10-08 54 views
0

我有社交媒体在ObservableCollectionRange的集合,我初始化如下:如何将Observable Collection的Item属性绑定到Switch状态?

public ObservableRangeCollection<SocialMediaEntity> CurrentSocialMedia { get; } = new ObservableRangeCollection<SocialMediaEntity>(); 

下面我获得的网络服务列表,然后我把这些元素集合中:

GetSonInformation().Subscribe((SonInformation) => 
       { 
        CurrentSon = SonInformation.Son; 
        CurrentSocialMedia.ReplaceRange(SonInformation.SocialMedia); 

       }); 

在页面上,如果令牌有效,并且如果令牌无效或者集合中没有这样的社交媒体,那么我希望启用一个切换组件。

<Switch Grid.Column="1" 
     VerticalOptions="Center" 
    HorizontalOptions="End" 
    IsToggled="{Binding Path=CurrentSocialMedia, 
    Converter={StaticResource SocialMediaStatusToBoolConverter}, 
    ConverterParameter={StaticResource youtubeKey}}"> 

    <Switch.Behaviors> 
     <behaviors:EventHandlerBehavior EventName="Toggled"> 
      <behaviors:InvokeCommandAction 
       Command="{Binding ToggleYoutubeSocialMediaCommand}" 
       Converter="{StaticResource SwitchChangeEventArgsConverter}"/> 

                </behaviors:EventHandlerBehavior> 

              </Switch.Behaviors> 
             </Switch> 

我遵循的方法是链接集合并使用一个转换器,它返回一个布尔值与我之前提到的逻辑。

public class SocialMediaStatusToBoolConverter : IValueConverter 
    { 

     public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
     { 

      IList<SocialMediaEntity> SocialMedias = (IList<SocialMediaEntity>)value; 

      if (SocialMedias == null || SocialMedias.Count() == 0) 
       return false; 

      var socialMedia = SocialMedias.SingleOrDefault(social => social.Type.Equals((string)parameter)); 

      return socialMedia != null && !socialMedia.InvalidToken; 
     } 


     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      return value; 
     } 
    } 

问题是这只是第一次完成。当我通过更换所有项目或添加另一个项目来更新集合时,什么都不更新。

任何人都可以告诉我我应该采取什么方法来做到这一点?提前致谢。

回答

1

由于Switch不打算要收集IsToggled属性,它不会监视收集改变的数据绑定事件。不像a Picker would do for ItemsSource.

所以,责任回到视图模型。基本上,视图模型需要确保每次更改集合时都会引发CurrentSocialMedia的属性更改事件。

对于e.g:

void OnPropertyChanged(object sender, PropertyChangedEventArgs args) 
{ 
    if(args.PropertyName != nameof(CurrentSocialMedia)) 
     return; 

    var oldObservable = oldValue as INotifyCollectionChanged; 
    if (oldObservable != null) 
     oldObservable.CollectionChanged -= CollectionChanged; 

    var newObservable = newValue as INotifyCollectionChanged; 
    if (newObservable != null) { 
     newObservable.CollectionChanged += CollectionChanged; 
    } 
} 

void CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) 
{ 
    RaisePropertyChanged(nameof(CurrentSocialMedia)); 
} 
1

我认为你必须执行INotifyPropertyChanged您SocialMediaEntity

相关问题