I have a style template (below) that does not update when my Tag binding updates. The data itself updates and I receive no binding errors so expect everything is bound correctly it is just that the style doesn't seem to update at all. I have notifypropertychanged events in all the right places afaik so doubt this is the issue.
Thanks
<Style x:Key="CompareTemplate" TargetType="TextBlock">
<!--Setter Property="Foreground" Value="#FF760000" /-->
<Setter Property="Foreground" Value="#FFBCBCBC" />
<Style.Triggers>
<Trigger Value="True" Property="Tag">
<Setter Property="Foreground" Value="#FF007602" />
</Trigger>
<Trigger Value="False" Property="Tag">
<Setter Property="Foreground" Value="#FF760000" />
</Trigger>
</Style.Triggers>
</Style>
And I use this template like so:
<TextBlock Style="{DynamicResource CompareTemplate}" Tag="{Binding UnitComparer.CommsID, FallbackValue=True}" Text="Comms ID:" />
Tag is of type object. I think that your Viewmodel assings a bool to it. WPF is able to convert between strings and objects but seemingly not between bool and object. One solution is to use a IValueConverter to change the bool to a string:
<Window x:Class="BindToTagSpike.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BindToTagSpike"
Title="Window1" Height="300" Width="300">
<StackPanel>
<StackPanel.Resources>
<local:ObjectToString x:Key="ObjectToString"/>
<Style x:Key="CompareTemplate" TargetType="TextBlock">
<Style.Triggers>
<Trigger Value="True" Property="Tag">
<Setter Property="Foreground" Value="Red" />
</Trigger>
<Trigger Value="False" Property="Tag">
<Setter Property="Foreground" Value="YellowGreen" />
</Trigger>
</Style.Triggers>
</Style>
</StackPanel.Resources>
<TextBlock Style="{StaticResource CompareTemplate}"
Name="TaggedTextBlock"
Tag="{Binding TagValue,
Converter={StaticResource ObjectToString}}"/>
<Button Click="Button_Click">Change Style</Button>
</StackPanel>
</Window>
using System;
using System.Windows;
using System.Windows.Data;
using System.ComponentModel;
namespace BindToTagSpike
{
public partial class Window1 : Window, INotifyPropertyChanged
{
public Window1()
{
InitializeComponent();
tagValue = false;
TaggedTextBlock.Text = "Test";
DataContext = this;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
TagValue=!TagValue;
}
private bool tagValue;
public bool TagValue
{
get { return tagValue; }
set
{
tagValue = value;
if (PropertyChanged != null)
PropertyChanged(this,new PropertyChangedEventArgs("TagValue"));
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
public class ObjectToString : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
}
Sometime when your template / style is not being applied as expected, WPF might not think the TargetType might matches the control type. Try the code below and see if that helps at all:
<Style x:Key="CompareTemplate" >
<!--Setter Property="Control.Foreground" Value="#FF760000" /-->
<Setter Property="Control.Foreground" Value="#FFBCBCBC" />
<Style.Triggers>
<Trigger Value="True" Property="Control.Tag">
<Setter Property="Control.Foreground" Value="#FF007602" />
</Trigger>
<Trigger Value="False" Property="Control.Tag">
<Setter Property="Control.Foreground" Value="#FF760000" />
</Trigger>
</Style.Triggers>
</Style>
Cheers,
Berryl
Related
I'm using this DataTrigger:
<Window x:Class="_11_5_Style_demo4_DataTrigger.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:_11_5_Style_demo4_DataTrigger"
mc:Ignorable="d"
Title="MainWindow" Height="130" Width="300">
<Window.Resources>
<local:L2BConverter x:Key="cvtr"/>
<!--TextBox DataTrigger-->
<Style TargetType="TextBox">
<Style.Triggers>
<DataTrigger Binding="{Binding
RelativeSource={x:Static RelativeSource.Self},
Path=Text.Length,
Converter={StaticResource cvtr},
UpdateSourceTrigger=PropertyChanged}"
Value="false">
<DataTrigger.Setters>
<Setter Property="BorderBrush" Value="Red"/>
<Setter Property="BorderThickness" Value="1"/>
</DataTrigger.Setters>
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel>
<TextBox Margin="5"/>
<TextBox Margin="5,0"/>
<TextBox Margin="5"/>
</StackPanel>
</Window>
I expected that the TextBox will have the red border when typed more than 6 characters, and UpdateSourceTrigger=PropertyChanged just not work when there are more than 6 characters in the TextBox. It updated only when lost focus.
Here is the Converter:
public class L2BConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int textLength = (int)value;
return textLength < 6 ? true : false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
I've googled, but didn't find relative problem. Can anybody explains why this not work, am I not using it right?
Your trigger is working correctly, but your expectations of the result of its work are not correct. The trigger correctly sets the border brush, but the problem is that the color of the border while the TextBox has focus is not taken from the TextBox.BorderBrush brush, but from the TextBox Template constant. And you can't change it with a trigger. You need to change the template of the TextBox itself or apply another way to solve your problem.
You can make sure that the trigger works correctly, for example, by changing the frame thickness:
<Style TargetType="TextBox">
<Style.Triggers>
<DataTrigger Binding="{Binding
RelativeSource={x:Static RelativeSource.Self},
Path=Text.Length,
Converter={StaticResource cvtr}}"
Value="false">
<DataTrigger.Setters>
<Setter Property="BorderBrush" Value="Red"/>
<Setter Property="BorderThickness" Value="10"/>
</DataTrigger.Setters>
</DataTrigger>
</Style.Triggers>
</Style>
Another way to implement such validation is to use a ValidationRule. But its use is only possible in a binding that you don't have. You can use a little "voodoo magic" for this:
public class LengthValidate : ValidationRule
{
public LengthValidate() :base(ValidationStep.UpdatedValue, true) { }
public int LengthLimit { get; set; }
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
int limit = LengthLimit;
if(value is BindingExpression expression)
{
value = expression.GetSourceValue();
}
if (value is not string text)
{
text= value?.ToString()?? string.Empty;
}
return text.Length <= limit
? ValidationResult.ValidResult
: new ValidationResult(false, $"String length exceeds limit={limit}.");
}
}
The GetSourceValue method from the BindingExpressionHelper class is used.
Style with this rule:
<Style TargetType="TextBox">
<Setter Property="Tag">
<Setter.Value>
<Binding Path="Text" RelativeSource="{RelativeSource Self}">
<Binding.ValidationRules>
<local:LengthValidate LengthLimit="6"/>
</Binding.ValidationRules>
</Binding>
</Setter.Value>
</Setter>
</Style>
I'm trying to bind <DataTemplate> on Telerik RadDiagram ShapeStyle:
<telerik:RadDiagram x:Name="Diagram"
ShapeStyle="{StaticResource NodeStyle}"
GraphSource="{Binding GraphSource}"/>
This style looks like this:
<Grid.Resources>
<Style x:Key="NodeStyle" TargetType="telerik:RadDiagramShape">
<Setter Property="Position" Value="{Binding Position, Mode=TwoWay}" />
<Setter Property="Content" Value="{Binding}" />
<Setter Property="Geometry" Value="{telerik:CommonShape ShapeType=RectangleShape}" />
<Setter Property="ContentTemplate" >
<Setter.Value>
<MultiBinding Converter="{StaticResource StyleConverter}">
<Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=UserControl}"/>
<Binding Path=""/>
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
...
</Grid.Resources>
StyleConverter:
class StyleConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
FrameworkElement targetElement = values[0] as FrameworkElement;
if (values[0] is BilledMsisdnViewModel)
return targetElement.FindResource("BilledMsisdnControl");
else if(values[0] is BilledImeiViewModel)
return targetElement.FindResource("ImeiControl");
return null;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Those resources (BilledMsisdnControl and ImeiControl) are defined in <UserControl.Resources>:
<UserControl.Resources>
<ResourceDictionary>
<local:BilledMsisdnControl x:Key="BilledMsisdnControl"/>
<local:ImeiControl x:Key="ImeiControl"/>
<local:StyleConverter x:Key="StyleConverter"/>
</ResourceDictionary>
</UserControl.Resources>
And they are created by me user controls.
So my goal here is according to binded view model type select user controll (this part works) and then use it as ContentTemplate (this don't work). I'm getting just object namespace nad name for ImeiControl or BilledMsisdnControl in diagram node.
How can I fix this?
According to the documentation you should use style selector
public class NodeStyleSelector : StyleSelector
{
public Style BilledMsisdnStyle { get; set; }
public Style BilledImeiStyle { get; set; }
public override Style SelectStyle(object item, DependencyObject container)
{
if (item is BilledMsisdnViewModel)
return BilledMsisdnStyle;
else if (item is BilledImeiViewModel)
return BilledImeiStyle;
else return base.SelectStyle(item, container);
}
}
Define styles with ContentTemplate. Inside ContentTemplate add your user controls.
<Style x:Key="BilledMsisdnStyle" TargetType="telerik:RadDiagramShape">
<Setter Property="Position" Value="{Binding Position, Mode=TwoWay}" />
<Setter Property="Content" Value="{Binding}" />
<Setter Property="Geometry" Value="{telerik:CommonShape ShapeType=RectangleShape}" />
<Setter Property="ContentTemplate" >
<Setter.Value>
<DataTemplate>
<local:BilledMsisdnControl/>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="BilledImeiStyle" TargetType="telerik:RadDiagramShape">
<Setter Property="Position" Value="{Binding Position, Mode=TwoWay}" />
<Setter Property="Content" Value="{Binding}" />
<Setter Property="Geometry" Value="{telerik:CommonShape ShapeType=RectangleShape}" />
<Setter Property="ContentTemplate" >
<Setter.Value>
<DataTemplate>
<local:ImeiControl/>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
Add shape style selector
<styleselectors:NodeStyleSelector x:Key="CustomShapeStyleSelector"
BilledMsisdnStyle="{StaticResource BilledMsisdnStyle}"
BilledImeiStyle="{StaticResource BilledImeiStyle}" />
Use ShapeStyleSelector for your RadDiagram.
<telerik:RadDiagram x:Name="Diagram"
ShapeStyleSelector="{StaticResource CustomShapeStyleSelecto}"
GraphSource="{Binding GraphSource}"/>
I need to change only the textcolor of a cell content, but my cell is binding by a list of entities that content a array property (that i need).
this is my code:
-- Entity:
public class MyEntity{
public string Name { get; set; }
public IList<string> Values { get; set; }
}
-- Datagrid and List
ObservableCollection<MyEntity> list;
// ....
DataGrid.ItemsSource = list;
-- Style
<Style x:Key="DgCellStyle" TargetType="DataGridCell">
<Style.Triggers>
<DataTrigger Binding="{Binding Values[{Binding self}]}" Value="KK">
<Setter Property="Foreground" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
-- If i use Binding="{Binding Values[2]}" it work, but the foregound is apply for the row (not the current cell).
you can achieve this by using IValueConverer
public class simpleListCheckConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null && ((List<String>)value).Contains((string)parameter))
{
return true;
}
else
{
return false;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
And Xaml :
<local:simpleListCheckConverter x:Key="simpleListCheckConverter1"/>
<Style x:Key="DgCellStyle" TargetType="DataGridCell">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Values, Converter={StaticResource simpleListCheckConverter1 },ConverterParameter=kk}" Value="true">
<Setter Property="Foreground" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
And For Row color change :
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Values, Converter={StaticResource simpleListCheckConverter1 },ConverterParameter=kk}" Value="true">
<Setter Property="Background" Value="Yellow" />
</DataTrigger>
</Style.Triggers>
</Style>
In a WPF project, I have a user control (Valve.xaml) that defines a Polygon shape.
<Grid>
<Polygon Name="pValve" Points="0,50 0,20 50,50 50,20" Style="{StaticResource Valve_Open}"/>
</Grid>
I am displaying the Valve user control in a window xaml (FFG.xaml) file, like such:
<Window
<!-- removed other namespaces for brevity -->
xmlns:cl="clr-namespace:FFG.Controls;assembly=PID.Controls">
<Grid>
<cl:Valve x:Name="valve201A"></cl:Valve>
</Grid>
</Window>
I am setting the DataContext of FFG.xaml to class FFG_ViewModel.cs, and it contains an instance of the Valve_Model class. Valve_Model essentially represents the valve that is drawn on the window in FFG.xaml.
public class FFG_ViewModel : ViewModelBase {
public Valve_Model Valve201A { get; set; }
// There are other properties and methods, but I've removed them for brevity also
}
Here is the Valve_Model class:
public class Valve_Model INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
private bool _isValveOpen { get; set; }
public bool IsValveOpen {
get {
return _isValveOpen;
}
set {
_isValveOpen = value;
OnPropertyChanged("IsValveOpen");
}
}
#region INotifyPropertyChanged
protected virtual void OnPropertyChanged(string propertyName) {
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null) {
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
#endregion
}
QUESTION:
What I want is for the Style property in the Valve.xaml to change when the IsValveOpen property changes.
So if the valve is open then it would be:
<Polygon Name="pValve" Points="0,50 0,20 50,50 50,20" Style="{StaticResource Valve_Open}"/>
and when the property is changed to false then I need the style of the polygon to be changed to:
<Polygon Name="pValve" Points="0,50 0,20 50,50 50,20" Style="{StaticResource Valve_Closed}"/>
How do I go about implementing this exactly?
You could use an IMultiValueConverter.
First, let's simplify the use case. Basicly you want to swap Styles based on a given state object, which I'll represent by a ToggleButton. The fact that you're wrapping everything in a UserControl also has no influence on the underlying concept.
Demo:
Starting a fresh project
Declaring our Resources
Feeding the Window and the state to the Converter.
MainWindow.xaml
<Window
...
>
<Window.Resources>
<local:ToStyleConverter x:Key="ToStyleConverter"/>
<Style x:Key="Valve_Open" TargetType="{x:Type Polygon}">
<Setter Property="Fill" Value="Red"/>
</Style>
<Style x:Key="Valve_Closed" TargetType="{x:Type Polygon}">
<Setter Property="Fill" Value="Green"/>
</Style>
</Window.Resources>
<DockPanel>
<ToggleButton x:Name="butt" DockPanel.Dock="Bottom">Switch</ToggleButton>
<Polygon Name="pValve" Points="0,50 0,20 50,50 50,20" Stretch="Uniform">
<Polygon.Style>
<MultiBinding Converter="{StaticResource ToStyleConverter}">
<Binding RelativeSource="{RelativeSource FindAncestor,
AncestorType={x:Type Window}}"/>
<Binding ElementName="butt" Path="IsChecked"/>
</MultiBinding>
</Polygon.Style>
</Polygon>
</DockPanel>
</Window>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
public class ToStyleConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
if (values[0] is Window)
{
Window win = (Window)values[0];
if ((bool)values[1])
return win.FindResource("Valve_Open");
if (!(bool)values[1])
return win.FindResource("Valve_Closed");
}
return DependencyProperty.UnsetValue;
}
public object[] ConvertBack(object values, Type[] targetType,
object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Changing to any specific use case means:
Pointing the relativesource binding to the Control that holds the Resources (Styles)
Using the second binding to add the state to the Converter (DP/INPC)
Implementing Converter logic
You can (should as much as I know) use a DataTrigger, within a ControlTemplate. Assuming that these two are your Styles:
<Window.Resources>
<Style TargetType="Polygon" x:Key="Valve_Open">
<Setter Property="Fill" Value="Red"/>
</Style>
<Style TargetType="Polygon" x:Key="Valve_Close">
<Setter Property="Fill" Value="Green"/>
</Style>
</Window.Resources>
You should add this style to the resources:
<Style x:Key="changeStyle" TargetType="Control">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Control">
<Grid>
<Polygon Name="pValve" Points="0,50 0,20 50,50 50,20" Style="{StaticResource Valve_Open}" />
</Grid>
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding Valve201A.IsValveOpen}" Value="true">
<Setter TargetName="pValve" Property="Style" Value="{StaticResource Valve_Close}" />
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
and use them in your views:
<Control DataContext="{Binding}" Style="{StaticResource changeStyle}" />
Instead of setting the actual Style property to a new value, you could add a DataTrigger to the Style itself that changes the properties of the Polygon based on the value of the IsValveOpen source property.
Valve.xaml:
<Grid>
<Polygon Name="pValve" Points="0,50 0,20 50,50 50,20">
<Polygon.Style>
<Style TargetType="Polygon">
<!-- Copy the setters from the Valve_Closed style here -->
<Setter Property="Fill" Value="Red" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsValveOpen}" Value="True">
<!-- Copy the setters from the Valve_Open style here -->
<Setter Property="Fill" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</Polygon.Style>
</Polygon>
</Grid>
FFG.xaml:
<Grid>
<cl:Valve x:Name="valve201A" DataContext="{Binding Valve201A}" />
</Grid>
i want to make a custom button using wpf. The button will be used to control a mediaplayer. the type(play, stop, pause,...) of the button is specified using an enum
namespace vgtunesWPF
{
public class MediaButton : Button
{
[Browsable(true)]
public Button_Type ButtonType
{
get { return (Button_Type)GetValue(ButtonTypeProperty); }
set { SetValue(ButtonTypeProperty, value); }
}
public static readonly DependencyProperty ButtonTypeProperty = DependencyProperty.Register("ButtonType", typeof(Button_Type), typeof(MediaButton), new FrameworkPropertyMetadata(Button_Type.stop, FrameworkPropertyMetadataOptions.AffectsRender, ImageSourceChanged));
static MediaButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MediaButton), new FrameworkPropertyMetadata(typeof(MediaButton)));
}
private static void ImageSourceChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
Application.GetResourceStream(new Uri("pack://application:,,," + (string) e.NewValue));
}
}
public enum Button_Type
{
play = 0,
pause = 1,
stop = 2,
forward = 3,
backward = 4
}
public class ButtonTypeConverter : IValueConverter
{
public object Convert(object value, Type TargetType, object Parameter, System.Globalization.CultureInfo culture)
{
if (value != null)
{
Button_Type type = (Button_Type)value;
switch (type)
{
case Button_Type.play:
return new BitmapImage(new Uri("/vgtunesWPF;component/Images/Play.png",UriKind.Relative));
case Button_Type.stop:
return new BitmapImage(new Uri("/vgtunesWPF;component/Images/Stop.png",UriKind.Relative));
default:
break;
}
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
In order to convert buttontype to the right image i created a converter.
then the XAML:
<Style TargetType="{x:Type local:MediaButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MediaButton}">
<Canvas Width="30" Height="30">
<Canvas.Resources>
<local:ButtonTypeConverter x:Key="Converter"/>
</Canvas.Resources>
<Image Name="Normal" Source="{Binding Source={StaticResource Converter}, Converter={StaticResource Converter},Path=}" />
<Image Name="Disabled" Visibility="Hidden" Source="/vgtunesWPF;component/Images/PlayDisabled.png"/>
</Canvas>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="Normal" Property="Visibility" Value="Visible"/>
<Setter TargetName="Normal" Property="Effect">
<Setter.Value>
<DropShadowEffect Color="AliceBlue" ShadowDepth="0" BlurRadius="15" />
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Normal" Property="Visibility" Value="Hidden"/>
<Setter TargetName="Disabled" Property="Visibility" Value="Visible"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
The problem here is that i want to bind ButtonType to the normal image, but i can't figure out how. I can't get ButtonType accessible in the xaml
Ok solved it. Apparently i had to add Relative source
<Image Name="Normal" Source="{Binding Converter={StaticResource Converter}, Path=ButtonType, RelativeSource={RelativeSource TemplatedParent}}" />
maybe you try to bind to your dependency property "ButtonType".
<Image Name="Normal" Source="{Binding ButtonType, Converter={StaticResource Converter}"/>