Reputation: 117
How to change property Fill of icon of current selected element in checkbox depending on IsChecked property?
My resource dictionary:
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<!-- (...) -->
</ResourceDictionary.MergedDictionaries>
<DataTemplate x:Key="FooTemplate">
<Icons:ExIcon Fill="Red"
Width="12"
Height="Auto">
<!--
<Icons:ExIcon.Triggers>
<DataTrigger Binding="{Binding RelativeSource={???}}, Path=???}" Maybe here?
Value="???"/>
</Icons:ExIcon.Triggers>
-->
</Icons:ExIcon>
</DataTemplate>
<!-- (...) -->
<styles:IconSelector x:Key="IconSelector"
FooTemplate="{StaticResource FooTemplate}"
FooTemplateSSecond="{StaticResource FooTemaplteSecond}"/>
And listbox:
<ListBox ItemsSource="{Binding DataSources}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<!-- (...) -->
<CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}">
<CheckBox.Template>
<!-- (...) -->
<ContentControl Name="Icon"
Content="{Binding}"
ContentTemplateSelector="{StaticResource IconSelector}"
HorizontalAlignment="Right"
Grid.Column="1"/>
<!-- (...) -->
</CheckBox.Template>
</CheckBox>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Is it possible?
Upvotes: 1
Views: 4861
Reputation: 2072
It's not completely clear to me how your CheckBox.Template
looks like. Also the Icons:ExIcon
Control is a mystery to me. Anyway here is a small working example. It uses a Rectangle instead of your ExIcon. But you can easily replace it ;-) I've bound directly to IsSelected
via a DataTrigger
instead of searching by ElementName
or RelativeSource
.
XAML:
<ListBox ItemsSource="{Binding}">
<ListBox.Resources>
<DataTemplate x:Key="template1">
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding Path=IsSelected}" />
<Rectangle Height="20"
Width="20">
<Rectangle.Style>
<Style TargetType="Rectangle">
<Setter Property="Fill"
Value="Blue" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsSelected}"
Value="True">
<Setter Property="Fill"
Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</Rectangle.Style>
</Rectangle>
</StackPanel>
</DataTemplate>
</ListBox.Resources>
<ListBox.ItemTemplate>
<DataTemplate>
<ContentControl ContentTemplate="{StaticResource template1}" Content="{Binding}">
</ContentControl>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
NOTE Content="{Binding}"
. This sets the DataContext
of the ContentPresenter
to the "actual" DataContext of the ListBoxItem
. If you use VS2015 you can investigate this with the VisualTreeViewer otherwise you can use https://snoopwpf.codeplex.com/
You should also consider to rename IsSelected
to IsChecked
. Noramlly you use the IsSelected
property for indicating if the row is selected or not.
Upvotes: 2