2
我制作了一个UWP自定义模板控件,它包含ICommandBarElement的集合,非常类似于标准的CommandBar控件。问题是,只要我点击我的CommandBar实现中包含的任何AppBarButton,就会发生未处理的异常:“没有支持这样的接口”。在我的自定义控件中单击按钮时发生异常
有一些我必须做错,但我不能看到它。下面是定制控件的代码:
public sealed class MyCommandBarControl : ContentControl
{
public MyCommandBarControl()
{
this.DefaultStyleKey = typeof(MyCommandBarControl);
this.PrimaryCommands = new ObservableCollection<ICommandBarElement>();
}
public ObservableCollection<ICommandBarElement> PrimaryCommands
{
get { return (ObservableCollection<ICommandBarElement>)GetValue(PrimaryCommandsProperty); }
set { SetValue(PrimaryCommandsProperty, value); }
}
/// <summary>
/// PrimaryCommands Dependency Property
/// </summary>
public static readonly DependencyProperty PrimaryCommandsProperty =
DependencyProperty.Register(
"PrimaryCommands",
typeof(ObservableCollection<ICommandBarElement>),
typeof(MainPage),
new PropertyMetadata(null, null));
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
var primaryItemsControl = GetTemplateChild("PrimaryItemsControl") as ItemsControl;
primaryItemsControl.ItemsSource = this.PrimaryCommands;
}
}
和相关风格:
<Style TargetType="local:MyCommandBarControl" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:MyCommandBarControl">
<Grid x:Name="LayoutRoot" Background="{TemplateBinding Background}">
<Grid x:Name="ContentRoot"
VerticalAlignment="{TemplateBinding VerticalAlignment}"
Margin="{TemplateBinding Padding}"
Height="{TemplateBinding Height}"
Background="{TemplateBinding Background}"
Opacity="{TemplateBinding Opacity}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ContentControl
x:Name="ContentControl"
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"
ContentTransitions="{TemplateBinding ContentTransitions}"
Foreground="{TemplateBinding Foreground}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
IsTabStop="False"
Margin="10, 0, 0, 0"/>
<ItemsControl
x:Name="PrimaryItemsControl"
IsTabStop="False"
Grid.Column="1"
Margin="10, 0, 0, 0"
HorizontalAlignment="Right"
HorizontalContentAlignment="Right">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Grid>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
我已经作出了small project you can download能重现问题。任何帮助解决这个例外,将不胜感激。
奇怪 - 我使用* AppBarButtons * *之外*命令栏和他们没有问题的工作。关于在命令栏以外的其他地方不使用这些控件的更多详细信息, – Romasz
你说得对。它可以在CommandBar之外使用。其实,我的意思是PrimaryCommands集合。我相信有一种办法可以做到OP所需要的,所以我仍在对此进行调查。我没有访问源代码,所以仍然不知道它背后有什么样的奥秘。将会更新,如果我找到了什么。 –
我也尝试使用* IObservableVector *而不是集合(像原始的PrimaryCommands),但它导致相同的异常。我不知道它在寻找什么样的界面。 – Romasz