我正在创建一个自定义控件,该控件具有-Command
类型的CommandProperty
,SelectedItems
和object
等其他属性,它们可能仅仅是对象或ObservableCollection<object>
取决于其他属性IsMultiSelect
。
这是android模拟器上的控件(它的ItemsSource
属性中有4个项目):
现在我需要将CommandParameter
绑定到SelectedItems
:
<controls:TogglesRow x:Name="TogRow"
ItemsSource="{Binding Items}" DisplayMemberPath="Name"
Command="{Binding ItemSelectedCommand}"
CommandParameter="{Binding Source={x:Reference TogRow},
Path=SelectedItems}"/>
但是问题在于它需要前一个SelectedItems
,这意味着在我第一次选择一个项目时,CommandParameter
是null
,下一次将选择第一个项目...等。
btn
是轻击按钮(自定义按钮),在UI属性(propertyChanged
,ItemsSourceProperty
等)的DisplayMemberPathProperty
委托中初始化。 :
//In the foreach that process the ItemsSource collection:
btn.SelectionChanged += (s, e) =>
{
if (IsMultiSelect)
{
if (btn.IsSelected)
(SelectedItems as ObservableCollection<object>).Add(item);
else
(SelectedItems as ObservableCollection<object>).Remove(item);
}
else
{
var allToggleButtons = stackContainer.Children.Where(x => x is ToggleButton);
allToggleButtons?.ForEach(x => ((ToggleButton)x).IsSelected = false);
btn.IsSelected = true;
SelectedItems = item;
}
if (!IsMultiSelect && btn.IsSelected)
SelectedItemsChanged?.Invoke(this, new TogglesRowSelectionChangedEventArgs
{
SelectedItems = SelectedItems,
SelectedIndices = ItemsSource.IndexOf(item)
});
else if (IsMultiSelect)
{
SelectedItemsChanged?.Invoke(this, new TogglesRowSelectionChangedEventArgs
{
SelectedItems = SelectedItems,
SelectedIndices = (SelectedItems as ObservableCollection<object>).Select(x => ItemsSource.IndexOf(x))
});
}
Command?.Execute(CommandParameter);
};
可绑定属性:
public static readonly BindableProperty CommandProperty =
BindableProperty.Create(nameof(Command), typeof(ICommand), typeof(TogglesRow), null);
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
public static readonly BindableProperty CommandParameterProperty =
BindableProperty.Create(nameof(CommandParameter), typeof(object), typeof(TogglesRow), null);
public object CommandParameter
{
get { return GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
public static readonly BindableProperty SelectedItemsProperty = BindableProperty.Create(nameof(SelectedItems), typeof(object), typeof(TogglesRow),
defaultBindingMode: BindingMode.TwoWay);
public object SelectedItems
{
get { return GetValue(SelectedItemsProperty); }
set { SetValue(SelectedItemsProperty, value); }
}
我知道,对CommandParameter
属性进行 late-bind 绑定是合理的,但无论如何。例如,重新评估绑定表达式以获取最新的SelectedItems
?