Я пытаюсь динамически связать панель команд с первичными командами. Вот XAML:
<CommandBar IsOpen="True"
Background="Transparent"
BorderBrush="Black"
Style="{StaticResource TagsCommandBar}"
DefaultLabelPosition="Right">
<interactivity:Interaction.Behaviors>
<local:BindableCommandBarBehavior PrimaryCommands="{x:Bind ViewModel.AppBarButtonList, Mode=OneWay}" />
</interactivity:Interaction.Behaviors>
</CommandBar>
И свойство зависимости для команд выглядит следующим образом:
public class BindableCommandBarBehavior : Behavior<CommandBar>
{
public ObservableCollection<AppBarButton> PrimaryCommands
{
get
{
return (ObservableCollection<AppBarButton>)GetValue(PrimaryCommandsProperty);
}
set
{
SetValue(PrimaryCommandsProperty, value);
}
}
public static DependencyProperty PrimaryCommandsProperty = DependencyProperty.Register(
"PrimaryCommands", typeof(ObservableCollection<AppBarButton>), typeof(BindableCommandBarBehavior), new PropertyMetadata(default(ObservableCollection<AppBarButton>), UpdateCommands));
private static void UpdateCommands(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
if (!(dependencyObject is BindableCommandBarBehavior behavior))
return;
if (dependencyPropertyChangedEventArgs.OldValue is INotifyCollectionChanged oldList)
{
oldList.CollectionChanged -= behavior.PrimaryCommandsCollectionChanged;
}
if (dependencyPropertyChangedEventArgs.NewValue is INotifyCollectionChanged newList)
{
newList.CollectionChanged += behavior.PrimaryCommandsCollectionChanged;
}
behavior.UpdatePrimaryCommands();
}
private void PrimaryCommandsCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
UpdatePrimaryCommands();
}
private void UpdatePrimaryCommands()
{
if (AssociatedObject == null)
return;
if (PrimaryCommands == null)
return;
AssociatedObject.PrimaryCommands.Clear();
if (!(PrimaryCommands is IEnumerable enumerable))
{
AssociatedObject.PrimaryCommands.Clear();
return;
}
if (PrimaryCommands != null)
{
AssociatedObject.PrimaryCommands.Clear();
foreach (var command in PrimaryCommands)
{
if (!AssociatedObject.PrimaryCommands.Contains(command))
{
try
{
AssociatedObject.PrimaryCommands.Add(command);
}
catch (Exception ex)
{
Log.D(this, ex.Message);
}
}
}
}
}
protected override void OnDetaching()
{
base.OnDetaching();
if (PrimaryCommands != null)
{
PrimaryCommands.CollectionChanged -= PrimaryCommandsCollectionChanged;
}
}
}
Этот код работает нормально, когда я динамически добавляю AppBarButtonList
. Но проблема возникает при загрузке сохраненных AppBarButtonList
. Это показывает исключение:
Element is already the child of another element.
at System.Runtime.InteropServices.WindowsRuntime.IVector`1.Append(T value)
at BindableCommandBarBehavior.UpdatePrimaryCommands()
Мне нужна любезная помощь, чтобы решить эту проблему и загрузить и добавить AppBarButtonList
.