Frage

I have this Image Button in my WPF Application:

<Button Grid.Column="2" Content="Play" Focusable="False" Width="100" Height="60" HorizontalAlignment="Left" VerticalAlignment="Center" Name="PlayPauseButton" Click="PlayPauseButton_Click">
    <Button.Template>
        <ControlTemplate>
            <Image x:Name="PlayPauseImage" Visibility="Visible" Stretch="Uniform" Source="/PlayTube;component/images/PlayerApplication/PlayButton.png" />
        </ControlTemplate>
    </Button.Template>
</Button>

And I want to have the ability to set the Image programmatically, but I can't access PlayPauseImage.

Any idea why it happen?

War es hilfreich?

Lösung 2

Try using FindName:

private void PlayPauseButton_Click(object sender, RoutedEventArgs e)
{
    Image image = (Image)PlayPauseButton.Template.FindName("PlayPauseImage", PlayPauseButton);
}

Note: Always use FindName only when the control will be fully loaded, otherwise it will not find it and give null.

Also for this event has:

ContentRendered for Window

Loaded

Andere Tipps

You can use FrameworkTemplate.FindName to locate control inside your ControlTemplate

var img = PlayPauseButton.Template.FindName("PlayPauseImage", PlayPauseButton) as Image;

Make sure the Button is Loaded.. so its better to use the Loaded event to get this...

private void ButtonBase_Loaded(object sender, EventArgs e)
{
    var image = PlayPauseButton.Template.FindName("PlayPauseImage", PlayPauseButton) as Image;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top