我在 ObservableCollectionRange 中有一个社交媒体集合,我初始化如下:
public ObservableRangeCollection<SocialMediaEntity> CurrentSocialMedia { get; } = new ObservableRangeCollection<SocialMediaEntity>();
下面我获得了这个 Web 服务列表,并将这些元素保存在集合中:
GetSonInformation().Subscribe((SonInformation) =>
{
CurrentSon = SonInformation.Son;
CurrentSocialMedia.ReplaceRange(SonInformation.SocialMedia);
});
在页面上,我有一个 Switch 组件,如果 token 有效,我希望启用该组件,如果 token 无效或集合中没有此类社交媒体,则该组件无效。
<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>
我采用的方法是链接集合并使用一个转换器,该转换器使用我之前提到的逻辑返回一个 bool 值。
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;
}
}
问题是这只是第一次完成。当我通过替换所有项目或添加另一个项目来更新集合时,没有任何更新。
谁能告诉我应该采取什么方法来做到这一点?提前致谢。
最佳答案
如Switch
不期待 IsToggled
的集合属性,它不会监视绑定(bind)数据上的集合更改事件。不像 a Picker
would do for ItemsSource
.
所以责任又回到了 View 模型。基本上, View 模型需要确保 CurrentSocialMedia
的属性更改事件每次更改集合时都会引发。
例如:
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));
}
关于c# - 如何将 Observable Collection 的 Item 属性绑定(bind)到 Switch 状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46629638/