Reputation: 25
I have a method like this:
public void vtornik ()
{
Image mon = (Image)Monday.Template.FindName("monday_2", Monday);
mon.Opacity = 0;
}
And i call it from my button click:
private void Thuesday_MouseUp(object sender, MouseButtonEventArgs e)
{
vtornik();
}
The template looks like this:
<Style x:Key="monday" TargetType="{x:Type ListBox}">
<Style.Resources>
<Storyboard x:Key="OnMouseLeftButtonUp1"/>
</Style.Resources>
<Style.Triggers>
<EventTrigger RoutedEvent="UIElement.MouseLeftButtonUp">
<BeginStoryboard Storyboard="{StaticResource OnMouseLeftButtonUp1}"/>
</EventTrigger>
</Style.Triggers>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBox}">
<ControlTemplate.Resources>
<Storyboard x:Key="OnMouseLeftButtonUp1">
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="monday_2">
<EasingDoubleKeyFrame KeyTime="0" Value="1"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</ControlTemplate.Resources>
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="ValidationStates">
<VisualState x:Name="Valid"/>
<VisualState x:Name="InvalidFocused"/>
<VisualState x:Name="InvalidUnfocused"/>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Image
x:Name="monday_1"
Source="images/monday_1.png"
Stretch="Fill"
Opacity="0"/>
<Image
x:Name="monday_2"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
Height="Auto" Width="Auto"
Margin="0" Source="images/monday_2.png"
Stretch="Fill" Opacity="0"/>
<ScrollViewer>
<ItemsPresenter/>
</ScrollViewer>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Opacity" TargetName="monday_1" Value="1"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Why can I successfully call this method from the button click but cant use it without button click?
I get NullReference exeption - method cant find image and then:
"An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll"
Upvotes: 1
Views: 627
Reputation: 1955
Make sure that the template is being applied (or the listbox you are trying to get the image from has loaded), to do this you could try a few different things.
You could use the FrameworkElement.OnApplyTemplate
Method to do what you need to do when the template has been applied.
When overridden in a derived class, is invoked whenever application code or internal processes call ApplyTemplate.
Or in some cases you could try calling the FrameworkElement.ApplyTemplate()
to try and force the element to apply its template.
Builds the current template's visual tree if necessary, and returns a value that indicates whether the visual tree was rebuilt by this call.
Upvotes: 1