I have a class called item and it contains only two properties. I will show them on the screen as buttons with style. This question is related to how I can style a button based on the IsSelected value when the element I want to touch is related to the style, not the data template. I already tried using Trigger but couldn't get it to work.
Class below.
public class Item : ObservableObject { private string _title; private bool _isSelected; public string Title { get { return _title; } set { _title = value; RaisePropertyChanged("Title"); } } public bool IsSelected { get { return _isSelected; } set { _isSelected = value; RaisePropertyChanged("IsSelected"); } } }
I am using a data template to display these items in ItemsControls.
<ItemsControl ItemsSource="{Binding Path=Items}" ItemTemplate="{StaticResource ResourceKey=ItemTemplate}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <StackPanel Orientation="Horizontal" /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> </ItemsControl>
Using the following style and data template.
<Style x:Key="ItemButton" TargetType="Button"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Button}"> <Border Name="ButtonBorder" BorderThickness="2,2,2,0" BorderBrush="#AAAAAA" CornerRadius="6,6,0,0" Margin="2,20,0,0" Background="Black"> <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center"/> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> <DataTemplate x:Key="ItemTemplate"> <Button Height="60" Style="{StaticResource ItemButton}" Name="Button"> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Path=Title}" HorizontalAlignment="Left" Margin="5,5,5,3" FontSize="25" Foreground="#6B6B6B" FontFamily="Arial" /> <Button Style="{StaticResource NoChromeButton}" Margin="0,0,5,0"> <Button.Content> <Image Height="20" Source="/WpfApplication1;component/Image/dialogCloseButton.png"></Image> </Button.Content> <Button.ToolTip> Close </Button.ToolTip> </Button> </StackPanel> </Button> </DataTemplate>
I need to change the background of the ButtonBorder from black to white when IsSelected is True on the Item object.
I added to the trigger in the data template This does not work, I think this is because the style overrides the DataTemplate, so the background remains white. But when I try to make a trigger in style, I can not access the IsSelected property?
Trigger DataTemplate
<DataTemplate.Triggers> <DataTrigger Binding="{Binding IsSelected}" Value="True"> <Setter TargetName="Button" Property="Background" Value="White"/> </DataTrigger> </DataTemplate.Triggers>
Style trigger
<Style.Triggers> <DataTrigger Binding="{Binding IsSelected}" Value="True"> <Setter Property="Background" Value="White"/> </DataTrigger> </Style.Triggers>
Am I missing something?