【发布时间】:2014-11-13 11:01:21
【问题描述】:
我的按钮有一个自定义模板,如下所示:
<!--Button Template-->
<Style TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="buttonBorderOuter"
BorderBrush="#DBDBDB"
BorderThickness="1"
Background="#00ECECEC"
CornerRadius="5"
Margin="1">
<Border x:Name="buttonBorderInner">
<TextBlock Text="{TemplateBinding Content}"
TextWrapping="Wrap"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Margin="{TemplateBinding Padding}">
<!--<ContentPresenter ContentSource="Content" />-->
</TextBlock>
</Border>
<Border.Triggers>
<EventTrigger RoutedEvent="MouseEnter">
<BeginStoryboard>
<Storyboard>
<ColorAnimation Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)"
To="#FFECECEC"
Duration="0:0:0" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="MouseLeave">
<BeginStoryboard>
<Storyboard>
<ColorAnimation Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)"
To="#00ECECEC"
Duration="0:0:0.5" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Border.Triggers>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsPressed"
Value="True">
<Setter Property="Background"
Value="#ECECEC"
TargetName="buttonBorderOuter" />
<Setter Property="BorderBrush"
Value="#FDFDFD"
TargetName="buttonBorderInner" />
<Setter Property="BorderThickness"
Value="1"
TargetName="buttonBorderInner" />
<Setter Property="CornerRadius"
Value="4"
TargetName="buttonBorderInner" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
该按钮几乎在任何情况下都可以正常工作。我可以悬停它并查看动画,我可以单击它并查看动画。唯一会引发错误的是当我单击按钮并将其从视图中移除时。
我正在编写一个 WPF 应用程序(您可能可以从上面代码中的 XAML 看出)它具有以下“命令”:
public ICommand AddEquipmentFilterToList
{
get
{
return new RelayCommand(
() =>
{
Equipment equipment = SegmentRequirementEquipment[SelectedEquipmentFilterIndex];
Button button = new Button();
button.Content = equipment.ID;
button.Padding = new Thickness(2.5);
button.Click += (o, i) =>
{
EquipmentFilters.Remove(button);
};
EquipmentFilters.Add(button);
});
}
}
在这里,我将一个按钮添加到与视图中的此控件链接的“ObservableCollection”:
<ItemsControl ItemsSource="{Binding EquipmentFilters}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
正如您在我的 C# 代码中看到的那样,当我单击按钮时,它应该从列表中删除,因此从视图中删除。当我这样做(单击按钮)时,出现以下错误:
“背景”属性未指向路径“(0).(1)”中的 DependencyObject
我认为这是因为“MouseLeave”事件触发但找不到“按钮”来更改其背景。
有没有办法解决这个错误,或者我的自定义模板设计不当?这是我第一次尝试编辑我的视觉演示文稿,并且很想学习如何做得更好。
【问题讨论】: