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.
Related
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>
...
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.
I have a ListBox of string items where I want to validate the strings every time a string is added or removed.
Below is the code I've cobbled together, but the problem is that ValidateAddresses is never called when the ObservableCollection Addresses changes.
Intended behavior is that when an invalid string is found, a red border should be shown around the ListBox with a tooltip that displays the error message.
This INotifyDataErrorInfo setup works fine for TextBoxes, so I dunno what I am doing wrong here.
ViewModel
[CustomValidation(typeof(ItemViewModel), "ValidateAddresses")]
public ObservableCollection<string> Addresses
{
get
{
return item.Addresses;
}
set
{
item.Addresses = value;
NotifyPropertyChanged(nameof(Addresses));
}
}
XAML
<Grid>
<Grid.Resources>
<Style TargetType="ListBox">
<Setter Property="Margin" Value="5"/>
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/>
<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate x:Name="TextErrorTemplate">
<DockPanel LastChildFill="True">
<AdornedElementPlaceholder>
<Border BorderBrush="Red" BorderThickness="2"/>
</AdornedElementPlaceholder>
<TextBlock Foreground="Red"/>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors).CurrentItem.ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
</Grid.Resources>
<ListBox ItemsSource="{Binding Path=Item.Addresses, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" SelectedIndex="{Binding Path=SelectedAddress, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
Validation method (never called)
public static ValidationResult ValidateAddresses(object obj, ValidationContext context)
{
ItemViewModel item = (ItemViewModel)context.ObjectInstance;
if (item.Addresses.Count > 0)
{
foreach (string address in item.Addresses)
{
if (Regex.IsMatch(address, #"[^\w]"))
return new ValidationResult($"{address} is not a valid address.", new List<string> { "Addresses" });
}
}
return ValidationResult.Success;
}
I ended up adding following in class constructor for each ObservableCollection I had.
Addresses.CollectionChanged += (sender, eventArgs) => { NotifyPropertyChanged(nameof(Addresses)); };
I tried to look into circumstances upon which unsubscribing from events is required to prevent memory leaks, but it does not seem like this is one of these cases so cleanup shouldn't be required.
Null check is not required because ObservableCollections are all initialized in Model class constructor.
Thank you for your replies.
And this is the code for NotifyPropertyChanged.
public class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
I'm displaying Cars in a DataGrid and would like to highlight one special car, the CurrentlySelectedCar.
When the user double clicks on a car, this car is saved as CurrentlySelectedCar in my MainViewModel. Now, whenever the user comes back to the DataGrid, I would like to highlight this car = row, e.g. by using a red background.
I have found out how to highlight rows in a DataGrid based on certain values, but in my case, all I have is the CurrentlySelectedCar.
My First try:
<Style TargetType="DataGridRow">
<Style.Triggers>
<!-- not working-->
<DataTrigger Binding="{Binding CurrentlySelectedCar}" >
<Setter Property="Background" Value="Red"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
My second try:
<Style TargetType="DataGridRow">
<Style.Triggers>
<!-- not working either, "Binding can only be set on DependencyProperty of DependecyObject"-->
<DataTrigger Binding="{Binding Guid}" Value="{Binding CurrentlySelectedCar.Guid}" >
<Setter Property="Background" Value="Red"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
How can I highlight the row with this information?
I think that you have to do something like this described in this answer: Using bindings in DataTrigger condition
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Value="True">
<DataTrigger.Binding>
<MultiBinding Converter="{StaticResource someMultiConverter}">
<Binding Path="Guid"></Binding>
<Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type Datagrid}}" Path="CurrentlySelectedCar.Guid"></Binding>
</MultiBinding>
</DataTrigger.Binding>
<Setter Property="Background" Value="Red"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
You have to write a multiconverter that return true if the two Guid are equals.
Try the following instead, since each datagrid row has an IsSelected property, you can bind to it directly.
<DataGrid EnableRowVirtualization="False">
<DataGrid.Resources>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding IsSelected}" >
<Setter Property="Background" Value="Red"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
</DataGrid>
Updated response
The problem right now is your DataContext is the DataGridRow, and it doesn't have access to the MainViewModel. You can address this by passing the DataGridRow to a converter that is aware of the current MainViewModel. However, it is a lot of code, and is barely comprehensible.
<Window>
<Window.Resources>
<local:IsCurrentlySelectedCarConverter x:Key="IsCurrentlySelectedCarConverter" />
</Window.Resources>
...
<DataTrigger Binding="{Binding
Path=DataContext,
Converter={StaticResource IsCurrentlySelectedCarConverter}}" >
<Setter Property="Background" Value="Red" />
</DataTrigger>
</Window>
Here's corresponding converter
public class IsCurrentlySelectedConverter : IValueConverter
{
public MainViewModel MainViewModel { get; set;}
public object Convert(object value, ....)
{
return (value == MainViewModel.CurrentlySelectedCar);
}
}
and you'll need to wire in the converter's MainViewModel manually in your view
this.Resources["IsCurrentlySelectedCarConverter"].MainViewModel = _mainViewModel;
and at this point you'd have to question the maintainability of the monster that has been created.
It may be better to replace each Car with a CarViewModel so that it has a property called IsSelected and you can maintain that in code. The following in my opinion is easier to follow what is actually going on.
public class CarViewModel : INotifyPropertyChanged
{
public MainViewModel { get; set; }
public bool IsSelected { get { return this == MainViewModel.CurrentlySelectedCar; } }
// Call RaisePropertyChanged("IsSelected") whenever
// CurrentlySelectedCar is changed
public void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName);
}
}
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>