DataTemplate check if Binding exist - c#

I had make an Button Style as DataTemplate in a ResourceDictionary. Here a small part:
<Style TargetType="{x:Type Button}">
<Setter Property="Focusable" Value="False"></Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="border">
...
</Border>
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding IsSelected}" Value="True">
<Setter Property="Background" TargetName="border" Value="Red" />
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
In this Template a have a binding to a Propertie IsSelected. This Propertie is in one situation there and in a other not.
Is it possible to Check in Xaml if the binding path exist, then use it in other case forget it?
Now i had BindingExpression in the Debug output and i want to eliminate this.

The more pertinent question is: why do you have a DataTrigger in your ControlTemplate? This creates a dependency between the control and its data context, which is why you're experiencing this issue when your data context does not match the control template's expectations.
Are you certain you cannot use a more suitable mechanism? For example, could you instead use a style for those buttons where IsSelected should affect the Background?
<Style x:Key="SpecialButtonStyle" TargetType="Button">
<Style.Triggers>
<DataTrigger Binding="{Binding IsSelected}" Value="True">
<Setter Property="Background" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
...
<Button DataContext="relevant data context" Style="{StaticResource SpecialButtonStyle}"/>
Or, even better, could you define a data template for the specific data class you have that has the IsSelected property? This data template could automatically use the correct Button style.

Related

XAML ContentControl not changing visibility

I have a little problem with my code. I have a content control that I want to switch the visibility on, based on a value of a property.
I have a toggle button that changes the value of the property IsListView and the icon without a problem.
<ToggleButton Width="26" Height="26" VerticalAlignment="Center" IsChecked="{Binding IsListView}" Command="{Binding SetItemsViewStyle}" Margin="0,0,5,0">
<ToggleButton.Style>
<Style TargetType="{x:Type ToggleButton}" BasedOn="{StaticResource MahApps.Styles.Button.Circle}">
<Setter Property="Content" Value="{iconPacks:BootstrapIcons List, Width=12, Height=12}" />
<Setter Property="ToolTip" Value="Switch to list display"/>
<Style.Triggers>
<Trigger Property="IsChecked" Value="true">
<Setter Property="Content" Value="{iconPacks:Material Apps, Width=12, Height=12}" />
<Setter Property="ToolTip" Value="Switch to tile display"/>
</Trigger>
</Style.Triggers>
</Style>
</ToggleButton.Style>
</ToggleButton>
Then I have a style for the content control that I would like to hide or display depending on the value of the IsListView property:
<Style x:Key="ListViewStyle" TargetType="ContentControl">
<Setter Property="Visibility" Value="Collapsed"/>
<Setter Property="Content" Value="{x:Null}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsListView}" Value="True">
<Setter Property="Visibility" Value="Visible"/>
<Setter Property="Content">
<Setter.Value>
<ScrollViewer HorizontalScrollBarVisibility="Disabled" VerticalAlignment="Stretch" VerticalScrollBarVisibility="Auto" Margin="0,31,0,0" >
<DataGrid ItemsSource="{Binding Projects}"/>
</ScrollViewer>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
The ContentControl is pretty much empty:
<ContentControl Style="{StaticResource ListViewStyle}">
</ContentControl>
The contents are displayed correctly when the screen is initialized (the IsListView is initialized to true), but the ContentControl does not dissapear when I click the toggle button. The code behind is executed, including fetching data from the data store, but the screen is not refreshed it seems to me.
What am I missing?
Ok, I found out what was the problem. I should have mentioned in my question that I am using ReactiveUI.
I had a property IsListView that was defined like this:
public bool IsListView { get; set; }
It has to be defined like this to ensure that the events are propagated to the view.
private bool _isListView;
public bool IsListView
{
get { return _isListView; }
set { this.RaiseAndSetIfChanged(ref _isListView, value); }
}
Now the controls hide and show as per my requirement.

Changing the style of a border inside data template for the listbox item based on the alterationindex [duplicate]

I have seen some articles that show how to use AlternationIndex with ListBoxes or ListViews, but I had spent a few hours trying to get alternating background colors on the base ItemsControl class and nothing seems to work. All ListBox samples I saw use ListBoxItem as the target type for the style that sets the background based onAlternationIndex - like this one from MSDN:
<Grid>
<Grid.Resources>
<Style x:Key="alternatingWithTriggers" TargetType="{x:Type ListBoxItem}">
<Setter Property="Background" Value="Blue"/>
<Setter Property="Foreground" Value="White"/>
<Style.Triggers>
<Trigger Property="ListBox.AlternationIndex" Value="1">
<Setter Property="Background" Value="CornflowerBlue"/>
<Setter Property="Foreground" Value="Black"/>
</Trigger>
<Trigger Property="ListBox.AlternationIndex" Value="2">
<Setter Property="Background" Value="LightBlue"/>
<Setter Property="Foreground" Value="Navy"/>
</Trigger>
</Style.Triggers>
</Style>
</Grid.Resources>
<ListBox AlternationCount="3" ItemsSource="{StaticResource data}"
ItemContainerStyle="{StaticResource alternatingWithTriggers}">
</ListBox>
</Grid>
I want to use the ItemsControl because I do not want the selection functionality and I think restyling a ListBox to hide it might not be the best choice.
This is one of the things I was trying:
<DataTemplate DataType="{x:Type vm:ObservableCollectionItem}">
<Grid>
<!-- some content here -->
</Grid>
</DataTemplate>
<!-- ... -->
<ItemsControl
ItemsSource="{Binding ObservableCollectionItems}"
AlternationCount="2"
>
<ItemsControl.ItemContainerStyle>
<Style>
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Grid.Background" Value="Red"></Setter>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Grid.Background" Value="Blue"></Setter>
</Trigger>
</Style.Triggers>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
The problem I saw was that the visual tree has a list of ContentPresenters that have ItemsControl.AlternationIndex alternate between 0 and 1, but the Grid in each ContentPresenter has ItemsControl.AlternationIndex set to 0.
There is probably something obvious I am missing...
The ItemContainerStyle is applied to the elements generated by the ItemsControl: ContentPresenter. The ContentPresenter will in turn contain whatever you put in your ItemTemplate. In the case of a ListBox, the ItemContainerStyle is applied to the generated ListBoxItem.
The AlternationCount is, based on what you posted, only available on these generated items. You cannot use the ItemContainerStyle to set the Grid's background, because the Grid is unknown to that Style.
The following would be ideal, but unfortunately ContentPresenter has no background property. It would work for a ListBox (with ListBoxItems) however.
<ItemsControl
ItemsSource="{Binding ObservableCollectionItems}"
AlternationCount="2">
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="Red"></Setter>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="Blue"></Setter>
</Trigger>
</Style.Triggers>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
So you end up writing a style for the grid which binds to the AlternationIndex of your parent ContentPresenter.
<DataTemplate DataType="{x:Type vm:ObservableCollectionItem}">
<Grid>
<Grid.Style>
<Style TargetType="Grid">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContentPresenter}}, Path=(ItemsControl.AlternationIndex)}" Value="0">
<Setter Property="Background" Value="Red"/>
</DataTrigger>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContentPresenter}}, Path=(ItemsControl.AlternationIndex)}" Value="1">
<Setter Property="Background" Value="Blue"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Grid.Style>
</Grid>
</DataTemplate>
hm... After about 2 hours of playing around, I finally found the solution that simply works:
<ItemsControl ItemsSource="{Binding}" AlternationCount="2">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Background="Transparent" x:Name="__PART_GRID"></Grid>
<DataTemplate.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter TargetName="__PART_GRID" Property="Background" Value="Red"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter TargetName="__PART_GRID" Property="Background" Value="Blue"/>
</Trigger>
</DataTemplate.Triggers>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
I hope this answer helps others to save some time.
Or, as I found on another post, and it works great for me...
You can simply use a binding...
{Binding
RelativeSource={RelativeSource Mode=TemplatedParent},
Path=(ItemsControl.AlternationIndex)}
NB: remember to add AlterationCount="100" on your ItemsControl
I don't know how any of the prior answers are legit. I couldn't make any of them work (didn't try Jacobi's though). Anyways, I found the path to enlightenment here: http://www.dotnetcurry.com/wpf/1211/wpf-items-control-advanced-topic, which lead me to adding the following in the xaml.cs code-behind:
public sealed class CustomItemsControl : ItemsControl
{
protected override DependencyObject GetContainerForItemOverride()
{
return new ContentControl();
}
}
and this in the xaml itself
<local:CustomItemsControl AlternationCount="2"
ItemsSource="{Binding Cells, Mode=OneWay}">
<local:CustomItemsControl.ItemContainerStyle>
<Style TargetType="ContentControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ContentControl">
<Border Background="{TemplateBinding Background}">
<ContentPresenter/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="WhiteSmoke"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="LightGray"/>
</Trigger>
</Style.Triggers>
</Style>
</local:CustomItemsControl.ItemContainerStyle>
</local:CustomItemsControl>
This was so damn hard to find a working solution to that I'm actually angry
If you don't want to use the DataTemplate approach, you can create a custom control that uses a ContentControl as the item container, therefore allowing you to specify a background color.
Class:
public class ItemsControlAlternating : ItemsControl
{
static ItemsControlAlternating()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(ItemsControlAlternating),
new FrameworkPropertyMetadata(typeof(ItemsControlAlternating)));
}
protected override DependencyObject GetContainerForItemOverride()
{
return new ContentControl();
}
protected override bool IsItemItsOwnContainerOverride(object item)
{
return item is ContentControl;
}
}
Resource Dictionary:
<Style TargetType="{x:Type c:ItemsControlAlternating}">
<Setter Property="AlternationCount" Value="2"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type c:ItemsControlAlternating}">
<ItemsPresenter/>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="{x:Type ContentControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ContentControl}">
<Border Background="{TemplateBinding Background}">
<ContentPresenter/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="Gray"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="White"/>
</Trigger>
</Style.Triggers>
</Style>
</Setter.Value>
</Setter>
</Style>

Is it possible to set the Items property of a WPF ComboBox in a style?

I have a form in WPF that requires a number of Yes/No comboboxes, databound to boolean properties on the viewmodel. As such, the item list is static. Rather than repeat it for every combobox, I was hoping to achieve this with a style; something like this:
<Style x:Key="trueFalseCombo" TargetType="{x:Type ComboBox}" BasedOn="{StaticResource ComboBoxStyle}">
<Setter Property="SelectedValuePath" Value="Tag"/>
<Setter Property="Items">
<Setter.Value>
<ComboBoxItem Tag="{StaticResource True}">Yes</ComboBoxItem>
<ComboBoxItem Tag="{StaticResource False}">No</ComboBoxItem>
</Setter.Value>
</Setter>
</Style>
But I receive the "Value is set more than once" error. I was thinking I needed to wrap in the items into some sort of collection container, but I couldn't figure out what. Is this even possible to do?
I realize I can make a simple custom control for this, but if it's not possible in a style I wanted a better understanding of why.
Set the ItemsSource property instead of Items. There is also no need for SelectedValue and SelectedValuePath if you use a collection of boolean values.
xmlns:sys="clr-namespace:System;assembly=mscorlib"
...
<Style x:Key="trueFalseCombo" TargetType="ComboBox">
<Setter Property="ItemsSource">
<Setter.Value>
<x:Array Type="sys:Boolean">
<sys:Boolean>True</sys:Boolean>
<sys:Boolean>False</sys:Boolean>
</x:Array>
</Setter.Value>
</Setter>
</Style>
In order to display Yes and No instead of True and False, you may use an ItemTemplate like this:
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<TextBlock>
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding}" Value="True">
<Setter Property="Text" Value="Yes"/>
</DataTrigger>
<DataTrigger Binding="{Binding}" Value="False">
<Setter Property="Text" Value="No"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</DataTemplate>
</Setter.Value>
</Setter>

Trigger doesn't work on ToggleButton.IsChecked property

Here is a simple XAML with trigger that should change ToggleButton content when it is checked. But for some reason it doesn't work. I have a silly feeling that I missed something extra small. Appreciate your help
<ToggleButton Content="<">
<ToggleButton.Style>
<Style TargetType="ToggleButton">
<Style.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Content" Value=">" />
</Trigger>
</Style.Triggers>
</Style>
</ToggleButton.Style>
</ToggleButton>
You must move Content="<" from ToggleButton to setter of Style.
Example:
<ToggleButton>
<ToggleButton.Style>
<Style TargetType="ToggleButton">
<Setter Property="Content" Value="<" />
<Style.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Content" Value=">" />
</Trigger>
</Style.Triggers>
</Style>
</ToggleButton.Style>
</ToggleButton>
Because local value has higher precedence order over Style setters and triggers:
Property system coercion.
Active animations, or animations with a Hold behavior.
3. Local value.
TemplatedParent template properties.
Implicit style.
6. Style triggers.
Template triggers.
8. Style setters.
...
For more information, please see:
MSDN: Dependency Property Value Precedence
You are overriding the Content set by the Trigger by setting the Content attribute at the control level. You want to set it using a Setter within the Style instead:
<ToggleButton>
<ToggleButton.Style>
<Style TargetType="ToggleButton">
<Setter Property="Content" Value="<" />
<Style.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Content" Value=">" />
</Trigger>
</Style.Triggers>
</Style>
</ToggleButton.Style>
</ToggleButton>

Change Button Background when is not enabled

I need to change my Button background (as SolidColorBrush for example) only when it is not enabled (IsEnabled == false). How can I do?
Have I to modify the Button Style using the XAML or can I do this work programmatically? What is the correct XAML code, to change only the Background when it is not enabled?
I tried the following XAML code but it has no effect:
<Button>
<Button.Style>
<Style TargetType="Button">
<Style.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Background" Value="Red"></Setter>
</Trigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
You can change the background by editing the template. You'll find the default template for Button here.
In the trigger for IsEnabled you can simply add something like this:
<Setter Property="Background" Value="{StaticResource DisabledBackgroundBrush}"/>
EDIT:
Try this instead then;
<Window.Resources>
<Style TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="Overlay" CornerRadius="2">
<ContentPresenter/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="false">
<Setter TargetName="Overlay" Property="Background" Value="Red"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<StackPanel>
<Button Content="Button" IsEnabled="False"/>
</StackPanel>
Just change it to suit your needs.
You can use a Style trigger:
<Image.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding IsEnabled}" Value="False">
<Setter Property="Image.Source" Value="pack://application:,,,/disabled.png" />
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>

Categories

Resources