I am try to Make a Image Button User control. But When I set image at window Initialize then throw this exception. Here is my Code
EXAM.
<UserControl.Resources>
<Style x:Key="ImageButton" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<StackPanel>
<Image x:Name="ButtonImage" Stretch="None"/>
<ContentPresenter Margin="0,8,0,0" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</StackPanel>
<ControlTemplate.Triggers>
<Trigger Property="IsFocused" Value="True"/>
<Trigger Property="IsDefaulted" Value="True"/>
<Trigger Property="IsMouseOver" Value="True"/>
<Trigger Property="IsPressed" Value="True"/>
<Trigger Property="IsEnabled" Value="False"/>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Button x:Name="ProcestaImageButton" Content="TextBlock" Style="{DynamicResource ImageButton}"/>
C# Code.
public ImageSource ButtonImage
{
get { return ((this.ProcestaImageButton.Template).FindName("ButtonImage", this.ProcestaImageButton) as Image).Source; }
set { ((this.ProcestaImageButton.Template).FindName("ButtonImage", this.ProcestaImageButton) as Image).Source = value; }
}
Please tell me where i am wrong.Please Provide me a Example.
Thank`s for Help.
For a start, I’d expand that property out – each statement is rather complicated at the moment. Here’s the expanded version:
I would then probably extract the common code to a helper property:
Next I would change the
asto a cast:At this point, you might still have a
NullReferenceExceptionor you might have aInvalidCastException– and suddenly you have a lot more information about what’s wrong.A cast is better here as you’re always expecting
FindNameto return anImage, aren’t you? If it’s an error condition for the type conversion to fail, you should use a cast – only useaswhen it’s valid for the expression not to be of the target type, and you’re intending to handle that case separately.