I am using IValueconverter interface to change the tooltip text of an image.
The tool tip should change based on label.
<Label Content="9898980001" Height="28" HorizontalAlignment="Left" Margin="1733,231,0,0" Name="lbl02scanning" VerticalAlignment="Top" Foreground="Blue" >
<Image Height="49" HorizontalAlignment="Right" Margin="0,131,113,0"
Name="img02scanning"
Source="/TEST;component/Images/LoadingStation.png" Stretch="Fill"
VerticalAlignment="Top" Width="30" Cursor="Hand">
<Image.ToolTip>
<StackPanel Background="AliceBlue">
<TextBlock Padding="5" Foreground="White" MinHeight="20"
Background="Blue" FontWeight="Bold"
Text="Scanning Station" />
<StackPanel Orientation="Horizontal">
<Image
Source="pack://application:,,,/TEST;component/Images/coilonsaddle_large.png"
Height="100" Width="100" />
<TextBlock Padding="10" TextWrapping="WrapWithOverflow"
MaxWidth="200" Background="AliceBlue"
Foreground="Black" FontWeight="Bold"
Text="{Binding ElementName=lbl02scanning, Path=Name,
ConverterParameter=255,
Converter={StaticResource FormatterFOrCoilToolTip}}"/>
</StackPanel>
<TextBlock Padding="5" Foreground="White" MinHeight="20"
Background="Blue" FontWeight="Bold"
Text="Report to admin in case of coil location mismatch"/>
</StackPanel>
</Image.ToolTip>
</Image>
The converter class:
public class FormatterForCoilToolTip : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if(parameter.ToString() == "02")
{
return value.ToString() + " Startin";
}
else
{
return value.ToString() + " Finishing";
}
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
The tooltip's Textblock content is not changing. But if i change to:
Text="{Binding ConverterParameter=255, Converter={StaticResource FormatterFOrCoilToolTip}}
then it is working. But i want to pass the lbl02scanning text value. Why it is not working??
First of all you should bind to Content property and not Name property in case you want Text of Label.
Most importantly Tooltip does not lies in same Visual Tree as that of label, hence binding with elementName won't work. However, you can use x:Reference to get the element even if it doesn't exist in same Visual Tree.
Text="{Binding Source={x:Reference lbl02scanning}, Path=Content,
ConverterParameter=255,
Converter={StaticResource FormatterFOrCoilToolTip}}"/>
Note - x:Reference is introduced in WPF 4.0. If you are using WPF 3.5 you can't use this.
Update for error - service provider is missing the name resolver service
Just found out bug is reported at Microsoft site that x:Reference fails in case Target is Label. However, i couldn't reproduce this issue at my end since i have WPF 4.5 installed at my end and i guess they have fixed the issue in future version.
In case you target WPF 4.0, i would advise you to use TextBlock in place of Label:
<TextBlock Text="9898980001" Height="28" HorizontalAlignment="Left"
Margin="1733,231,0,0" Name="lbl02scanning" VerticalAlignment="Top"
Foreground="Blue" />
and then bind with Text property instead of Content.
Text="{Binding Source={x:Reference lbl02scanning}, Path=Text,
ConverterParameter=255,
Converter={StaticResource FormatterFOrCoilToolTip}}"/>
Either, you can refer to workaround provide under workarounds section here.
You can override the ProvideValue method of the Reference class and skip the reference search login in design time:
[ContentProperty("Name")]
public class Reference : System.Windows.Markup.Reference
{
public Reference()
: base()
{ }
public Reference(string name)
: base(name)
{ }
public override object ProvideValue(IServiceProvider serviceProvider)
{
IProvideValueTarget valueTargetProvider = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
if (valueTargetProvider != null)
{
DependencyObject targetObject = valueTargetProvider.TargetObject as DependencyObject;
if (targetObject != null && DesignerProperties.GetIsInDesignMode(targetObject))
{
return null;
}
}
return base.ProvideValue(serviceProvider);
}
Update with another workaround
This will work for all versions WPF 3.5, WPf 4.0 and WPF 4.5.
First of all bind Image Tag with content of label.
Second host your stackPanel inside ToolTip control so that you can
take benefit of PlacementTarget property.
Third bind with PlacementTarget.Tag of Tooltip.
Relevant code will look like this:
<Image Tag="{Binding ElementName=lbl02scanning,Path=Content}">
<Image.ToolTip>
<ToolTip>
<TextBlock Text="{Binding RelativeSource={RelativeSource
Mode=FindAncestor, AncestorType=ToolTip},
Path=PlacementTarget.Tag,
ConverterParameter=255,
Converter={StaticResource FormatterFOrCoilToolTip}}"/>
</ToolTip>
</Image.ToolTip>
</Image>
Also you need to update converter code to put null check over there since PlacementTarget will be null until you open tooltip.
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
if (value != null)
{
if (parameter.ToString() == "02")
{
return value.ToString() + " Starting";
}
else
{
return value.ToString() + " Finishing";
}
}
return String.Empty;
}
Try This
Text="{Binding Path=Content,ElementName=lbl02scanning, ConverterParameter=255, Converter={StaticResource FormatterFOrCoilToolTip}}
Related
As of now, i assign the image of a TreeView item using a direct binding to the image's source:
<DataTemplate DataType="{x:Type local:GeoPoint}">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Color}" Height="32" />
<TextBlock Text="{Binding Name}" VerticalAlignment="Center"/>
</StackPanel>
</DataTemplate>
the Color binding is referring to string containing the path to the PNG, something like "/Resources/red.png"
i would like to make the Color variable of custom type "MarkerColor", an enum containing several colors, and have the image source binding reference this value, so that if
Color = MarkerColor.green; the binding would reference "/Resources/green.png"
Note that the name of the PNG is not necessarily the same as the name of MarkerColor, an "adapter" should be used to convert the type
I know how to do this in Java Android SDK, but not really sure on how to achive this in Wpf
You could create a converter that knows how to convert the enumeration value to a valid resource:
public class ColorResourceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
MarkerColor color = (MarkerColor)value;
Uri uri;
switch(color)
{
case MarkerColor.Green:
uri = new Uri("Resources/green.png");
break;
case MarkerColor.Red:
uri = new Uri("Resources/red.png");
break;
//...
default:
uri = new Uri("Resources/default.png");
break;
}
return new BitmapImage(uri);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
Usage:
<DataTemplate DataType="{x:Type local:GeoPoint}">
<DataTemplate.Resources>
<local:ColorResourceConverter x:Key="ColorResourceConverter" />
</DataTemplate.Resources>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Color, Converter={StaticResource ColorResourceConverter}}" Height="32" />
<TextBlock Text="{Binding Name}" VerticalAlignment="Center"/>
</StackPanel>
</DataTemplate>
I'm developing a small application that needs to check some availability properties. I'm using for the user interface WPF. I need to change some foreground colors if a selection from a combobox. I have this DataTemplate:
<DataTemplate x:Key="userTemplate">
<TextBlock VerticalAlignment="Center">
<Image Source="imgsource.png" Height="25" Width="25" />
<Run Text="{Binding BooleanObjectName}" Foreground="{Binding boolobject, Converter={StaticResource convAvailability}}"/>
</TextBlock>
So I'm using for this convertion a IValueConverter that sets the color to the foreground:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
BooleanObject boolobject = (BooleanObject)value;
if (boolobject.IsBoolValueOne) return System.Drawing.Brushes.Green;
else if (boolobject.IsBoolValueTwo) return System.Drawing.Brushes.Red;
else if (boolobject.IsBoolValueThree) return (SolidColorBrush)(new BrushConverter().ConvertFrom("#d3d300"));
else return System.Drawing.Brushes.Black;
}
What is wrong with this, because in my interface I'm always getting the black color. Any thoughts on this ?
Any help would be very much appreciated.
Thanks in advance.
As pointed out by #Funk you return the wrong kind of brushes. You should return a System.Windows.Media.Brush object:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
BooleanObject boolobject = (BooleanObject)value;
if (boolobject.IsBoolValueOne)
return System.Windows.Media.Brushes.Green;
else if (boolobject.IsBoolValueTwo)
return System.Windows.Media.Brushes.Red;
else if (boolobject.IsBoolValueThree)
return (SolidColorBrush)(new BrushConverter().ConvertFrom("#d3d300"));
return System.Windows.Media.Brushes.Black;
}
Then it should work provided that your binding to the boolobject property actually works. Otherwise your converter won't get invoked at all.
If you want to bind to the object itself, you should specify a path of '.':
<TextBlock VerticalAlignment="Center">
<Image Source="imgsource.png" Height="25" Width="25" />
<Run Text="{Binding BooleanObjectName}" Foreground="{Binding Path=., Converter={StaticResource convAvailability}}"/>
</TextBlock>
I am new in WPF I want validate my IP address but I have a problem: when I try to show the error message, it shows me only an empty red border.
Here is the ControlTemplate and all the code:
<Window x:Class="SOTCBindingValidation.Window1"
x:Name="This"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SOTCBindingValidation"
Title="SOTC Validation Test" Height="150" Width="400">
<Window.Resources>
<local:ErrorsToMessageConverter x:Key="eToMConverter"/>
<ControlTemplate x:Key="customvalidatortemplate">
<StackPanel Orientation="Horizontal">
<Border BorderThickness="1" BorderBrush="Red" VerticalAlignment="Top">
<Grid>
<AdornedElementPlaceholder x:Name="adorner" Margin="-1"/>
</Grid>
</Border>
<Border x:Name="errorBorder" Background="Red" Margin="8,0,0,0"
CornerRadius="0" IsHitTestVisible="False">
<TextBlock Text="{Binding ElementName=AddressBox,
Path=(Validation.Errors),
Converter={StaticResource eToMConverter}}"
Foreground="White" FontFamily="Segoe UI"
Margin="8,2,8,3" TextWrapping="Wrap"
VerticalAlignment="Center"/>
</Border>
</StackPanel>
</ControlTemplate>
</Window.Resources>
<StackPanel Margin="5">
<TextBlock Margin="2">Enter An IPv4 Address:</TextBlock>
<TextBox x:Name="AddressBox"
Validation.ErrorTemplate="{StaticResource customvalidatortemplate}"
Margin="0,0,235.5,0">
<TextBox.Text>
<Binding ElementName="This" Path="IPAddress"
UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:IPv4ValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</StackPanel>
</Window>
ErrorsToMessageConverter.cs file :
public class ErrorsToMessageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var sb = new StringBuilder();
var errors = value as ReadOnlyCollection<ValidationError>;
if (errors != null)
{
foreach (var e in errors.Where(e => e.ErrorContent != null))
{
sb.AppendLine(e.ErrorContent.ToString());
}
}
return sb.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
IPv4ValidationRule.cs file :
public class IPv4ValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
var str = value as string;
if (String.IsNullOrEmpty(str))
{
return new ValidationResult(false,
"Please enter an IP Address.");
}
var parts = str.Split('.');
if (parts.Length != 4)
{
return new ValidationResult(false,
"IP Address should be four octets, seperated by decimals.");
}
foreach (var p in parts)
{
int intPart;
if (!int.TryParse(p, NumberStyles.Integer, cultureInfo.NumberFormat, out intPart))
{
return new ValidationResult(false,
"Each octet of an IP Address should be a number.");
}
if (intPart < 0 || intPart > 255)
{
return new ValidationResult(false,
"Each octet of an IP Address should be between 0 and 255.");
}
}
return new ValidationResult(true, null);
}
}
I've found the solution (after a sleep:). In fact the exact element source you have to bind to can be accessed via the AdornedElementPlaceholder. It has a property called AdornedElement, TemplateBinding does not work in this case because TemplatedParent does not point to the TextBox, it's just another Control which is used for ErrorTemplate control. So the code should be like this:
<TextBlock Text="{Binding ElementName=adorner,
Path=AdornedElement.(Validation.Errors),
Converter={StaticResource eToMConverter}}"
Foreground="White" FontFamily="Segoe UI" Margin="8,2,8,3"
TextWrapping="Wrap" VerticalAlignment="Center"/>
Note about how we set the attached property Validation.Errors for the AdornedElement. Also note about the name adorner which is exactly the name you set for the AdornedElementPlaceholder. I've made a demo and surely it should work.
I just finished with watching practical mvvm presentation video on youtube and if I understand correctly moving logic from codebehing to view model is good practice and we should strive to this pattern.
Having this in mind I have one simple question. Inside xaml I have four radio buttons
<StackPanel x:Name="panel">
<RadioButton GroupName="myGroup" Name="Option1" Content="option one" IsChecked="True" Width="40"/>
<RadioButton GroupName="myGroup" Name="Option2" Content="option two" IsChecked="False" Width="80"/>
<RadioButton GroupName="myGroup" Name="Option3" Content="option three" IsChecked="False" Width="60"/>
</StackPanel>
I want to use this code inside viewmodel below to fetch selected radio btn.
var checkedValue = panel.Children.OfType<RadioButton>()
.FirstOrDefault(r => r.IsChecked.HasValue && r.IsChecked.Value);
Question is: How can I access to this panel object from the viewmodel? It's not data to use binding.
Update:
as #Rohit Vatss said "View objects should not be accessed from ViewModel" I would change question to How to know which radio button is selected using viewmodel?
You can do it by creating one property in you ViewModel, lets say GroupIndex
private int _groupIndex = 1;
public int GroupIndex
{
get { return _groupIndex; }
set
{
if (_groupIndex == value) return;
_groupIndex = value;
OnPropertyChanged("GroupIndex");
}
}
then create simple converter which will convert current GroupIndex value to true or false and back:
public class IndexBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || parameter == null)
return false;
else
return (int)value == System.Convert.ToInt32(parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || parameter == null)
return null;
else if ((bool)value)
return System.Convert.ToInt32(parameter);
else
return DependencyProperty.UnsetValue;
}
}
and then bind your RadioButton to GroupIndex which will will be set to 1, 2 or 3 depending on which RadioButton is checked
<StackPanel>
<StackPanel.Resources>
<local:IndexBooleanConverter x:Key="IndexBooleanConverter"/>
</StackPanel.Resources>
<RadioButton Content="Option1" IsChecked="{Binding Path=GroupIndex, Converter={StaticResource IndexBooleanConverter}, ConverterParameter=1}"/>
<RadioButton Content="Option2" IsChecked="{Binding Path=GroupIndex, Converter={StaticResource IndexBooleanConverter}, ConverterParameter=2}"/>
<RadioButton Content="Option3" IsChecked="{Binding Path=GroupIndex, Converter={StaticResource IndexBooleanConverter}, ConverterParameter=3}"/>
</StackPanel>
In this case GroupIndex is int but you can also use same logic if for example your GroupIndex is an enum
Well an aprroach would be for example using a Command and a Command Parameter on the radiobuttons Binded to your viewmodel. For example:
<RadioButton GroupName="myGroup" Name="Option1" Content="option one" IsChecked="True" Width="40" Command="{Binding RbCheckedCommand}" CommandParameter="RB1"/>
<RadioButton GroupName="myGroup" Name="Option2" Content="option two" IsChecked="False" Width="80" Command="{Binding RbCheckedCommand}" CommandParameter="RB2"/>
<RadioButton GroupName="myGroup" Name="Option3" Content="option three" IsChecked="False" Width="60" Command="{Binding RbCheckedCommand}" CommandParameter="RB3"/>
Then on your ViewModel:
private readonly DelegateCommand<object> rbCheckedCommand;
public ICommand RbCheckedCommand
{
get { return this.rbCheckedCommand; }
}
private void RbCheckedCommandExecute(object obj)
{
string rbselected = obj.ToString();
}
And on the constructor of the class:
this.rbCheckedCommand = new DelegateCommand<object>(RbCheckedCommandExecute);
You will have to use the prism adding:
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.ViewModel;
And making your class inherits from NotificationObject so you can use the Property changed easily.
Hope it helps.
I am looking to get a specific behavior on TextBlock so that its height only includes the height of the capital letters (from baseline to top minus "ascender height"). Please see the image Sphinx from Wikipedia to see what I mean. Also the image below may indicate better what I am after.
I am not specifically looking for a pure XAML solution (probably impossible) so a C# code behind (a converter) is also fine.
This is the XAML used in XamlPad to produce the left A in the image above.
<TextBlock Text="A" Background="Aquamarine" FontSize="120" HorizontalAlignment="Center" VerticalAlignment="Center" />
u can try to use attribute LineStackingStrategy="BlockLineHeight" and a Converter on the LineHeight attributes and a converter on the Height of TextBlock.
This a sample code of converters
// Height Converter
public class FontSizeToHeightConverter : IValueConverter
{
public static double COEFF = 0.715;
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return (double)value * COEFF;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
// LineHeightConverter
public class FontSizeToLineHeightConverter : IValueConverter
{
public static double COEFF = 0.875;
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return double.Parse(value.ToString()) * COEFF;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
The Coefficient used on converters depends on Used Family Fonts (Baseline and LineSpacing):
<TextBlock Text="ABC" Background="Aqua" LineStackingStrategy="BlockLineHeight"
FontSize="{Binding ElementName=textBox1, Path=Text}"
FontFamily="{Binding ElementName=listFonts, Path=SelectedItem}"
Height="{Binding RelativeSource={RelativeSource Self}, Path=FontSize, Mode=OneWay, Converter={StaticResource FontSizeToHeightConverter1}}"
LineHeight="{Binding RelativeSource={RelativeSource Self}, Path=FontSize, Converter={StaticResource FontSizeToLineHeightConverter}}"/>
The best solution is to find how to calculate the Coeff based on parameters Baseline and LineSpacing of the FontFamily.
In this sample (Segeo UI) the Coeff of Height = 0.715 and LineHeight = 0,875 * FontSize.
Updated:
If I understand right, there's a few tricks I know for this,
You can Scale it with RenderTransform which is usually the most efficient way;
<TextBlock Text="Blah">
<TextBlock.RenderTransform>
<CompositeTransform ScaleY="3"/>
</TextBlock.RenderTransform>
</TextBlock>
Or you can embed the TextBlock in a Viewbox to "zoom" the text to fit the bounds of its container if for example you set hard height values on grid rows like;
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="120"/>
<RowDefinition Height="120"/>
</Grid.RowDefinitions>
<Viewbox VerticalAlignment="Stretch" Height="Auto">
<!-- The textblock and its contents are
stretched to fill its parent -->
<TextBlock Text="Sphinx" />
</Viewbox>
<Viewbox Grid.Row="2" VerticalAlignment="Stretch" Height="Auto">
<!-- The textblock and its contents are
stretched to fill its parent -->
<TextBlock Text="Sphinx2" />
</Viewbox>
or you can bind the FontSize to a Container element like;
<Grid x:Name="MyText" Height="120">
<TextBlock FontSize="{Binding ElementName=MyText, Path=Height}" Text="Sphinx" />
</Grid>
They might present the effect you're after?