Multiple values single data trigger WPF - c#

I have the following piece of code.
<Button.Style>
<Style BasedOn="{StaticResource {x:Static ToolBar.ButtonStyleKey}}"
TargetType="{x:Type Button}">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<DataTrigger Binding="{Binding Status, Mode=OneWay}"
Value="{x:Static comm:DeviceStatus.Standby}">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
<DataTrigger Binding="{Binding Status, Mode=OneWay}"
Value="{x:Static comm:DeviceStatus.Busy}">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
<DataTrigger Binding="{Binding Status, Mode=OneWay}"
Value="{x:Static comm:DeviceStatus.Offline}">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
<DataTrigger Binding="{Binding Status, Mode=OneWay}"
Value="{x:Static comm:DeviceStatus.StartingStream}">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
<DataTrigger Binding="{Binding Status, Mode=OneWay}"
Value="{x:Static comm:DeviceStatus.Connecting}">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
<DataTrigger Binding="{Binding Status, Mode=OneWay}"
Value="{x:Static comm:DeviceStatus.Disconnecting}">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
<DataTrigger Binding="{Binding Status, Mode=OneWay}"
Value="{x:Static comm:DeviceStatus.DownloadingFiles}">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
The button is hidden by default and is visible when a property in the viewmodel has one out of a few values. The property is of an enum type called DeviceStatus.
Basically it conducts an OR operation on the provided triggers.
So, the visibility of the button is determined by: Status == StandBy || Status == Busy || ...
How can I implement this without having to have 8 triggers?
I would like to have something like the following:
<DataTrigger Binding="{Binding Status, Mode=OneWay}">
<DataTrigger.AnyValue>
<AnyValueItem Value="{x:Static comm:DeviceStatus.Standby}" />
<AnyValueItem Value="{x:Static comm:DeviceStatus.Busy}" />
<AnyValueItem Value="{x:Static comm:DeviceStatus.Offline}" />
...
</DataTrigger.AnyValue>
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
Where the Visibility of the Button is set to Visible if the binding gets ANY of the supplied values.
Thanks!

After reading the answers I got some ideas and found a satisfying extendable solution.
First I created the following converter.
public sealed class EnumOrConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
DeviceStatus status = (DeviceStatus)value;
DeviceStatus[] statuses = parameter as DeviceStatus[];
if (statuses.Any(s => s == status))
{
return Visibility.Visible;
}
else
{
return Visibility.Collapsed;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Second I simply added the following code to the XAML.
<Button Command="{Binding SomeCommand}">
<Button.Style>
<Style BasedOn="{StaticResource {x:Static ToolBar.ButtonStyleKey}}"
TargetType="{x:Type Button}">
<Setter Property="Visibility">
<Setter.Value>
<Binding Path="Status" Converter="{StaticResource EnumOrConverter}">
<Binding.ConverterParameter>
<x:Array Type="{x:Type comm:DeviceStatus}">
<x:Static Member="comm:DeviceStatus.Standby" />
<x:Static Member="comm:DeviceStatus.Busy" />
<x:Static Member="comm:DeviceStatus.Offline" />
<x:Static Member="comm:DeviceStatus.StartingStream" />
<x:Static Member="comm:DeviceStatus.Connecting" />
<x:Static Member="comm:DeviceStatus.Disconnecting" />
<x:Static Member="comm:DeviceStatus.DownloadingFiles" />
</x:Array>
</Binding.ConverterParameter>
</Binding>
</Setter.Value>
</Setter>
</Style>
</Button.Style>
</Button>
This allows me to reuse the converter logic for many other buttons and no adding of variables or properties to the ViewModel. What also happened is that the converter encapsulates the logic of "OR:ing" the parameters and "defaulting to Visibility.Collapsed". And adding a new parameter simply requires one line of code in XAML which is where it belongs.

The DataTrigger has no support for some kind of list of possible values. It only has a single Value property.
The easiest way to work around this would be to add a property to the view model that returns a value that indicates whether to display the Button:
public bool IsVisible => Status == Standby || Status == Busy || ...;
XAML:
<DataTrigger Binding="{Binding IsVisible, Mode=OneWay}" Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
Another option may be to use a converter as suggested by #l33t. You would then simply move the logic out of the view model, e.g.:
public class Converter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
ViewModel vm = value as ViewModel;
return (vm != null && (vm.Status == Standby || vm.Status == Busy || ...)) ? Vsibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
XAML:
<Style ...>
<Style.Resources>
<local:Converter x:Key="conv" />
</Style>
<Setter Property="Visibility" Value="{Binding Path=., Converter={StaticResource converter}}" />

You could just make a property:
private DeviceStatus _Status;
public DeviceStatus Status
{
get { return _Status; }
set
{
this.Set(ref _Status, value);
RaisePropertyChanged(nameof(this.StatusVisibility));
}
}
public Visibility StatusVisibility
{
get
{
switch (_Status)
{
case DeviceStatus.Busy: //add other statuses here
return Visibility.Visible;
}
return Visibility.Collapsed;
}
}
and then in your button:
<Button Content="MyButton" Visibility="{Binding StatusVisibility}"></Button>

For others. An answer that's similar to Lugvig W's answer but keeps with DataTriggers and is more generalised
ValueConverter
public sealed class AnyMatchConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (parameter is Array objects && value is not null)
{
return Array.BinarySearch(objects, value) != -1;
}
return DependencyProperty.UnsetValue;
}
...
XAML
<DataTrigger Value="True">
<DataTrigger.Binding>
<Binding Path="Status" Converter="{StaticResource AnyMatchConverter}">
<Binding.ConverterParameter>
<x:Array Type="{x:Type comm:DeviceStatus}">
<x:Static Member="comm:DeviceStatus.Standby" />
<x:Static Member="comm:DeviceStatus.Busy" />
...
</x:Array>
</Binding.ConverterParameter>
</Binding>
</DataTrigger.Binding>
...

Related

DataTrigger is not setting the opacity

I have a datagrid with data trigger.
<Style TargetType="{x:Type DataGridRow}" BasedOn="{StaticResource {x:Type DataGridRow}}">
<Setter Property="ContextMenu" Value="{StaticResource RowMenu}" />
<Setter Property="IsSelected" Value="{Binding IsSelected}" />
<Setter Property="Opacity" Value="1"/>
<Style.Triggers>
<DataTrigger x:Uid="DataTrigger_1" x:Name="RowMenuDataTrigger" Binding="{Binding IsModified, diag:PresentationTraceSources.TraceLevel=High}" Value="True">
<Setter x:Uid="Setter_1" Property="Opacity" Value="0.5" />
<Setter x:Uid="Setter_2" Property="ToolTip">
<Setter.Value>
<MultiBinding x:Uid="MultiBinding_1" Converter="{StaticResource ModifiedTypeMessage}">
<Binding x:Uid="Binding_1" Path="Class"></Binding>
<Binding x:Uid="Binding_2" Path="OriginalClassName" ></Binding>
</MultiBinding>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</control:DataGrid.RowStyle>
and IMultiValueConverter looks like:
public class EnTypeModifiedMessageConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values.Length == 2)
{
string current = values[0].ToString();
string original = values[1].ToString();
if (current != original)
{
return string.Format(LanguageHelper.LocalizedString("RawTypeModified"), original.ToUpper());
}
}
return string.Empty;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
return null;
}
}
when the data changes I get the control hitting this converter. but the UI still not updated. ie opacity and tooltip remains same.

WPF bind background color of DataGridTextColumn to color by row

Say I have a DataGrid with the following data:
John, Male
Mary, Female
Tony, Male
Sally, Female
The grid is bound to an ObservableCollection of Person model objects that implements INofifyPropertyChanged for the properties Person.Name and Person.Gender. I now want to bind the DataGridTextColumn's background color to the person's gender so that rows containing males are blue, and rows containing females are pink. Is it possible to do this by adding another property to the Person model like so:
public class Person
{
public Color BackgroundColor
{
get
{
if (gender == "Male")
{
return Color.Blue;
}
else
{
return Color.Pink;
}
}
}
if so, how do I bind this to the row or column's background color? I already have bounded columns like this:
<DataGridColumn Header="Name" Binding={Binding Name} />
<DataGridColumn Header="Gender" Binding={Binding Gender} />
Assuming that BackgroundColor is of a System.Windows.Media.Color type, and not System.Drawing.Color, if you want to change background of the entire row you can alter DataGrid.RowStyle and bind Background property to BackgroundColor property
<DataGrid ...>
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="{Binding Path=BackgroundColor}"/>
</Setter.Value>
</Setter>
</Style>
</DataGrid.RowStyle>
</DataGrid>
You want to implement an IValueConverter to convert a String to a Brush. See http://www.wpf-tutorial.com/data-binding/value-conversion-with-ivalueconverter/
public class StringToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var val = (string)value;
return new SolidColorBrush(val == "male" ? Colors.Blue : Colors.Pink);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
In XAML, you'll want <Window.Resources> like
<Window.Resources>
<local:StringToBrushConverter x:Key="stringToBrush" />
<Style x:Key="MaleFemaleStyle" TargetType="DataGridCell">
<Setter Property="Background" Value="{Binding Path=Gender, Converter={StaticResource stringToBrush}}" />
</Style>
</Window.Resources>
Then apply the MaleFemaleStyle to your grid.
<DataGrid CellStyle="{StaticResource MaleFemaleStyle}">
...
</DataGrid>
This works for me
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Style.Triggers>
<DataTrigger Binding="{Binding Sex}" Value="Male">
<Setter Property="Background" Value="Blue"/>
</DataTrigger>
<DataTrigger Binding="{Binding Sex}" Value="Female">
<Setter Property="Background" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>

Data trigger not firing off correct string value

So here's the idea.
If the textbox is empty, 'DataTrigger' should set the outline (BorderBrush) to red.
If the textbox is not empty / has text; then the dataTrigger should set the BorderBrush to Blue.
xmlns:conv="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<!-- conv is referenced in the "clr-namespace:WpfApplication1" namespace. It's bassically a referal to a converter I'm using -->
<conv:IsNullConverter x:Key="isNullConverter"/>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<!-- if the textbox is empty, then the setter should set the border colour to red-->
<DataTrigger Binding="{Binding Words, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource isNullConverter}}" Value="True">
<Setter Property="BorderBrush" Value="Red"/>
</DataTrigger>
<!-- If it has text inside it, setter should set the border colour to blue -->
<DataTrigger Binding="{Binding Words, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource isNullConverter}}" Value="False">
<Setter Property="BorderBrush" Value="Blue"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<TextBox x:Name="first" FontSize="14" TabIndex="1" Background="Black" BorderThickness="5" Foreground="White" Margin="29,10,132,272" />
</Grid>
Because it's not possible for datatriggers to see if a value is NOT null indipendently, I had to add some code to help it do that.
using System.Windows.Data;
using System.Globalization;
using System.ComponentModel;
namespace WpfApplication1
{
public class IsNullConverter : IValueConverter, INotifyPropertyChanged
{
// The string that the 'conv:' checks against
private string FOO;
// The DataTriggrer is bound to 'Words'
public string Words
{
get
{
return FOO;
}
set
{
if (FOO != value)
{
FOO = value;
RaisePropertyChanged("Words");
}
}
}
private void RaisePropertyChanged(string prop)
{
if (PropertyChanged == null)
{
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public string Error
{
get { return null; }
}
// This is the 'Convert' Parameter conv checks against. Here is the problem is
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
//This checks against the FOO string at the top of this class. Not the FOO in 'Words' get & set string
if (FOO == null)
{
value = true;
}
// So even if 'Words' raises the property changed, The origional FOO string remains unaffected.
// So the Datatrigger is never fired
if (FOO != null)
{
value = false;
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new InvalidOperationException("IsNullConverter can only be used OneWay.");
}
}
}
The thing is if I append the string FOO like;
private string FOO = "Something";
The Datatrigger fires at runtime and changes the outline colour to blue.
But I need the colour to be based on the textbox content rather than what I directly declare the string as.
I tried binding the data Trigger to the 'Words' string but the outline colour remains red, empty or not.
And suggestions? I really don't mind if I have to completely throw this code upside down if there's a better way of doing it.
Here you go:
<TextBox x:Name="first" FontSize="14" TabIndex="1" Background="Black" BorderThickness="5" Foreground="White" Margin="29,10,132,272">
<TextBox.Style>
<Style TargetType="TextBox">
<Setter Property="BorderBrush" Value="Blue"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Text, RelativeSource={RelativeSource Self}}" Value="">
<Setter Property="BorderBrush" Value="Red"/>
</DataTrigger>
<DataTrigger Binding="{Binding Text, RelativeSource={RelativeSource Self}}" Value="{x:Null}">
<Setter Property="BorderBrush" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
Bind to the TextBox.Text property by using RelativeSource:
<DataTrigger Binding="{Binding Text, RelativeSource={RelativeSource Self}, Converter={StaticResource isNullConverter}}" Value="True">
<!--apropriate setter-->
</DataTrigger>
This trigger sets the BorderBrush if Text is empty. To set the border brush when Text is not empty, just use normal Setter, without DataTrigger.
Also, note that within your ValueConverter you should use String.IsNullOrEmpty instead of plain NULL comparison.
You can simplify your converter to look something like
public class IsNullConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return String.IsNullOrEmpty((string) value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new InvalidOperationException("IsNullConverter can only be used OneWay.");
}
}
and then in style bind TextBox.Text via converter
<Window.Resources>
<conv:IsNullConverter x:Key="isNullConverter"/>
<Style TargetType="{x:Type TextBox}">
<Setter Property="BorderBrush" Value="Blue"/>
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Text, Converter={StaticResource isNullConverter}}" Value="True">
<Setter Property="BorderBrush" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
this will work but only if TextBox is not focused as then default template will take over and change BorderBrush. You can make it work but then you'll need to change default template as well where simpliest template would be another Setter in your Style
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<Border
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
BorderThickness="{TemplateBinding BorderThickness}">
<ScrollViewer x:Name="PART_ContentHost"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>

Check in Data Trigger if object is particular class

Is there a way to check in DataTrigger if the object is of a particular class?
In fact I would like that DataTrigger answer this question in C#:
if(MyObject is MyClass)
I want it to look something like this in XAML:
<Grid>
<Grid.Triggers>
<DataTrigger Binding="{Binding MyObject}" Value="MyClass?">
<Setter..../>
</DataTrigger>
</Grid.Triggers>
</Grid>
You can use a converter for this:
<Grid>
<Grid.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding MyString, Converter={StaticResource OConv}, ConverterParameter=System.String}" Value="True">
<Setter Property="Grid.Background" Value="Red"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</Grid.Style>
</Grid>
Use the ConverterParameter to state the type of the object you expect to receive...
Converter will return true if it matches or false otherwise...
Example of converter:
public clas s ObjectTypeToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value.GetType().ToString() == (string)parameter)
{
return true;
}
return false;
}

How can I use 3 different styles based on two unrelated triggers

I have a Gridview.Column where the style of the content is changed depending on the content of another column by a IMultiValueConverter. This part works as expected.
If the values of the two values are the same then the text of this column is LightGray otherwise black.
<GridViewColumn Header="New Name" Width="300">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding newFileName}">
<TextBlock.Style>
<Style>
<Setter Property="TextBlock.Foreground" Value="Black"></Setter>
<Style.Triggers>
<DataTrigger Value="True">
<DataTrigger.Binding>
<MultiBinding Converter="{StaticResource FileNameColorConverter}">
<!--<Binding Path="Selected"/>-->
<Binding Path="newFileName"/>
<Binding Path="fileName"/>
</MultiBinding>
</DataTrigger.Binding>
<Setter Property="TextBlock.Foreground" Value="LightGray"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
Now I have another property in this object that is bound to this GridView. If this is TRUE the text of this column should become red, instead of black, if it is false, the FileNameColorConverter should decide the style of the column, same as it is now.
How can I do this? I am at the moment lost, and have no idea where to put this logic, I am quite sure there is a way to have this also in XAML.
Edit
What I tried is adding another trigger after the first one, but it didn't worked for me, if this is the way to go, whats wrong with my code?
I added this after my first </DataTrigger> but it didn't had an effect.
<DataTrigger Value="True">
<DataTrigger.Binding>
<Binding Path="FileNameError"/>
</DataTrigger.Binding>
<Setter Property="TextBlock.Foreground" Value="Red"></Setter>
</DataTrigger>
Multiple data triggers with exclusive conditions on same data work for me perfectly... Can you check if your FileNameError is True for atleast 1 item? And if are you changing it dynamically then are you raising PropertyChanged event?
You can try my code and see...
XAML:
<Page.Resources>
<local:MultiBindingConverter x:Key="MultiBindingConverter"/>
<coll:ArrayList x:Key="MyData">
<local:Student Id="1" local:Student.Name="Test1" Active="False"/>
<local:Student Id="2" local:Student.Name="Test2" Active="True"/>
<local:Student Id="3" local:Student.Name="Test3" Active="False"/>
<local:Student Id="4" local:Student.Name="Test4" Active="False"/>
</coll:ArrayList>
</Page.Resources>
<Grid>
<ListBox ItemsSource="{StaticResource MyData}"
DisplayMemberPath="Name">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Style.Resources>
<SolidColorBrush
x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="Yellow"/>
</Style.Resources>
<Style.Triggers>
<DataTrigger Value="True">
<DataTrigger.Binding>
<MultiBinding
Converter="{StaticResource
MultiBindingConverter}">
<Binding Path="Id"/>
<Binding Path="Active"/>
</MultiBinding>
</DataTrigger.Binding>
<Setter Property="Foreground" Value="Red"/>
</DataTrigger>
<DataTrigger Value="3">
<DataTrigger.Binding>
<Binding Path="Id"/>
</DataTrigger.Binding>
<Setter Property="Foreground" Value="Blue"/>
</DataTrigger>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Foreground" Value="Gray"/>
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</Grid>
Code Behind:
public class MultiBindingConverter : IMultiValueConverter
{
#region IMultiValueConverter Members
public object Convert(object[] values, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
if (values[0] != DependencyProperty.UnsetValue
&& values[0] != null && values[1] != null)
{
var value1 = (int)values[0];
var value2 = (bool)values[1];
var result = (value1 > 1 && value2);
if (result)
{
return true;
}
return false;
}
return false;
}
public object[] ConvertBack
(object value, Type[] targetTypes,
object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
public class Student : INotifyPropertyChanged
{
public int Id
{
get;
set;
}
public string Name
{
get;
set;
}
public bool Active
{
get;
set;
}
public Student()
{ }
public Student(int id, string name)
{
this.Id = id;
this.Name = name;
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
Add another trigger after the existing one which triggers on the additional property with Value="True". This should then override the existing trigger if the property is true, allowing you to set the column to be red. However, if the property is false the trigger will do nothing and the existing trigger's effects will be visible.
Look into the GridViewColumn.CellTemplateSelector Property.
Depending on some logic, the DataTemplateSelector, you give the cell a different DataTemplate.

Categories

Resources