I’m trying to create an ImageToggleButton for my WinRT project that changes it’s image in respect to its IsChecked property.
In the designer of Visual Studio 2012 and Visual Studio Express for Windows 8 the ToggleButton behaves as expected, but during run time the image does not get displayed.
Any ideas?
XAML:
<Page.Resources>
<local:BooleanImageConverter x:Name="BoolImgConverter"/>
</Page.Resources>
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<ToggleButton HorizontalAlignment="Left" Height="200" Margin="260,205,0,0" VerticalAlignment="Top" Width="833" Background="Yellow">
<Image Source="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Parent.IsChecked, Converter={StaticResource BoolImgConverter}, ConverterParameter=Assets/chkMusic}"/>
</ToggleButton>
</Grid>
CodeBehind:
public class BooleanImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string culture)
{
bool state = (bool)value;
string baseName = (string)parameter;
return string.Format("{0}_{1}checked.png", baseName, state ? "" : "un");
}
public object ConvertBack(object value, Type targetType, object parameter, string culture)
{
return null;
}
}
Code description:
I’d put an Image control into the ToggleButton and bind the image source to the IsChecked property of the containing (parent) ToggleButton using a converter that decorates the given ConverterParameter according IsChecked to provide the string to reference the desired image file.
Sure I could do this in code behind, but I would prefer to do it in XAML as much as possible.
At the moment I’m also not after building a ControlTemplate and I would have tried RelativeSource FindAncestor and other suggestions of this forum, but these dids not seem to work in Windows Store Apps (or am I wrong?).
I’d appreciate any suggestions.
Thanks
(BTW: I tried to add windows-store-app as tag to this post, but could not create this new tag – would someone else do this)
Parent has never worked as you think it would. There are a couple of ways to accomplish what you need.
The first is to keep the RelativeSource binding but remove the Path to IsChecked. This will pass the control to the converter. In it you can get the parent using the VisualTreeHelper.
The second is to name your ToggleButton and bind to it using ElementName binding