Set background depending on a value in WPF - c#

I need to set the background value depending on a value that you receive in the constructor.
The types are:
public enum EToastType
{
Error,
Info,
Success,
Warning
}
CustomMessage.xaml:
<core:NotificationDisplayPart x:Class="Presentacion.Notificaciones.CustomMessage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:core="clr-namespace:ToastNotifications.Core;assembly=ToastNotifications"
mc:Ignorable="d" Background="{**I NEED SET VALUE**}"
d:DesignHeight="60" d:DesignWidth="250">
<Grid Margin="5">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Title}" FontWeight="Bold" Foreground="White" />
<TextBlock Text="{Binding Message}" FontWeight="Light" Foreground="White" Grid.Row="1" TextWrapping="Wrap" />
</Grid>
CustomMesage.xaml.cs:
public partial class CustomMessage : NotificationDisplayPart
{
public CustomMessage(ToastDto toast)
{
DataContext = toast;
InitializeComponent();
}
}
ToastDto.cs:
public class ToastDto
{
public EToastType Color { get; set; }
public string Title { get; set; }
public string Message { get; set; }
}
And App.xaml:
<Application
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib"
xmlns:options="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options">
<Application.Resources>
<ResourceDictionary>
<Color x:Key="InformationColor">#147ec9</Color>
<SolidColorBrush x:Key="InformationColorBrush" Color="{StaticResource InformationColor}" options:Freeze="True" />
<Color x:Key="SuccessColor">#11ad45</Color>
<SolidColorBrush x:Key="SuccessColorBrush" Color="{StaticResource SuccessColor}" options:Freeze="True" />
<Color x:Key="ErrorColor">#e60914</Color>
<SolidColorBrush x:Key="ErrorColorBrush" Color="{StaticResource ErrorColor}" options:Freeze="True" />
<Color x:Key="WarningColor">#f5a300</Color>
<SolidColorBrush x:Key="WarningColorBrush" Color="{StaticResource WarningColor}" options:Freeze="True" />
</ResourceDictionary>
</Application.Resources>
Then depending on the EToastType value that is sent to the CustomMessage constructor, the background property in CustomMessage has to take a value of App.xaml

You can write a custom IValueConverter to convert your EToastType to Brush.
public class EToastTypeToBrushConverter : IValueConverter
{
public Brush Error { get; set; }
public Brush Info { get; set; }
public Brush Success { get; set; }
public Brush Warning { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is EToastType type)
{
switch (type)
{
case EToastType.Error:
return Error;
case EToastType.Info:
return Info;
case EToastType.Success:
return Success;
case EToastType.Warning:
return Warning;
}
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> throw new NotSupportedException();
}
By using this converter, just initialize a new instance with each brush property in your resource dictionary.
<local:EToastTypeToBrushConverter x:Key="EToastTypeToBrushConverter"
Info="{StaticResource InformationColorBrush}"
Success="{StaticResource SuccessColorBrush}"
Error="{StaticResource ErrorColorBrush}"
Warning="{StaticResource WarningColorBrush}"/>
EDIT: If you want a more universal IValueConverter, you can write such code instead of EToastTypeToBrushConverter:
[ContentProperty(nameof(Conversions))]
public class EnumToObjectConverter : IValueConverter
{
public Collection<EnumConversion> Conversions { get; } = new Collection<EnumConversion>();
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
=> Conversions.FirstOrDefault(x => Equals(x.Source, value))?.Target;
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> throw new NotSupportedException();
}
But in this way, XAML usage will be more complex:
<local:EnumToObjectConverter x:Key="EToastTypeToBrushConverter">
<local:EnumConversion Target="{StaticResource InformationColorBrush}">
<local:EnumConversion.Source>
<local:EToastType>Info</local:EToastType>
</local:EnumConversion.Source>
</local:EnumConversion>
<local:EnumConversion Target="{StaticResource SuccessColorBrush}">
<local:EnumConversion.Source>
<local:EToastType>Success</local:EToastType>
</local:EnumConversion.Source>
</local:EnumConversion>
<local:EnumConversion Target="{StaticResource ErrorColorBrush}">
<local:EnumConversion.Source>
<local:EToastType>Error</local:EToastType>
</local:EnumConversion.Source>
</local:EnumConversion>
<local:EnumConversion Target="{StaticResource WarningColorBrush}">
<local:EnumConversion.Source>
<local:EToastType>Warning</local:EToastType>
</local:EnumConversion.Source>
</local:EnumConversion>
</local:EnumToObjectConverter>

Related

Change image source dynamically (StaticResource)

I want to change the image displayed in a grid depending on a certain condition (e.g. an enum value). The problem is that the image sources are DrawingImage (provided from xaml file).
<Grid>
<Image Source="{StaticResource BodyDrawingImage}"></Image>
</Grid>
I want that BodyDrawingImage (which is a key for DrawingImage) to be selected at run-time (by a binding i guess) from a list of DrawingImage keys but I can't figure out how to do this.
The way I've handled this is using a value converter class, with a property corresponding to each element of the Enum type.
public class perDialogIconConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is perDialogIcon))
{
return null;
}
switch ((perDialogIcon) value)
{
case perDialogIcon.Asterisk:
return AsteriskIcon;
case perDialogIcon.Error:
return ErrorIcon;
case perDialogIcon.Exclamation:
return ExclamationIcon;
case perDialogIcon.Hand:
return HandIcon;
case perDialogIcon.Information:
return InformationIcon;
case perDialogIcon.Question:
return QuestionIcon;
case perDialogIcon.Stop:
return StopIcon;
case perDialogIcon.Warning:
return WarningIcon;
default:
return null;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
public UIElement AsteriskIcon { get; set; }
public UIElement ErrorIcon { get; set; }
public UIElement ExclamationIcon { get; set; }
public UIElement HandIcon { get; set; }
public UIElement InformationIcon { get; set; }
public UIElement QuestionIcon { get; set; }
public UIElement StopIcon { get; set; }
public UIElement WarningIcon { get; set; }
}
This is instantuated as a resource within the window, along with each image required
<Window.Resources>
<Image x:Key="AsteriskIcon"
Source="Images/Asterisk.png"
Stretch="None" />
<Image x:Key="ErrorIcon"
Source="Images/Error.png"
Stretch="None" />
<Image x:Key="ExclamationIcon"
Source="Images/Exclamation.png"
Stretch="None" />
<Image x:Key="HandIcon"
Source="Images/Hand.png"
Stretch="None" />
<Image x:Key="InformationIcon"
Source="Images/Information.png"
Stretch="None" />
<Image x:Key="QuestionIcon"
Source="Images/Question.png"
Stretch="None" />
<Image x:Key="StopIcon"
Source="Images/Stop.png"
Stretch="None" />
<Image x:Key="WarningIcon"
Source="Images/Warning.png"
Stretch="None" />
<dlg:perDialogIconConverter x:Key="DialogIconConverter"
AsteriskIcon="{StaticResource AsteriskIcon}"
ErrorIcon="{StaticResource ErrorIcon}"
ExclamationIcon="{StaticResource ExclamationIcon}"
HandIcon="{StaticResource HandIcon}"
InformationIcon="{StaticResource InformationIcon}"
QuestionIcon="{StaticResource QuestionIcon}"
StopIcon="{StaticResource StopIcon}"
WarningIcon="{StaticResource WarningIcon}" />
</Window.Resources>
and then used as required as part of the binding statement - DialogIcon is an enum property on the ViewModel
<ContentPresenter Grid.Row="0"
Grid.Column="0"
VerticalAlignment="Center"
Content="{Binding DialogIcon, Converter={StaticResource DialogIconConverter}}" />

UWP Binding to Visibility property of a FontIcon

I'm trying to bind the Visibility property of a FontIcon to an enum property in my view model using a converter, but for some reason it throws an exception
Unable to cast object of type 'Windows.UI.Xaml.Controls.FontIcon' to type
'Windows.UI.Xaml.Data.Binding'
What I want to achieve is that depending on the current value of CurrentSortOrder hide or show an icon inside the MenuFlyoutItem
View model code:
public class TestViewModel : ViewModelBase
{
private TaskSortType _currentTaskSortOrder = TaskSortType.BY_NAME_ASC;
public TaskSortType CurrentSortOrder
{
get => _currentTaskSortOrder;
set => Set(ref _currentTaskSortOrder, value);
}
}
View:
<Page
x:Class="UWPTests.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:converters="using:UWPTests.Converters"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="using:UWPTests"
xmlns:localModels="using:UWPTests.Models"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
DataContext="{x:Bind ViewModel}"
mc:Ignorable="d">
<Page.Resources>
<converters:TaskSortTypeToVisibilityConverter x:Key="TaskSortTypeToVisibilityConverter" />
</Page.Resources>
<Grid>
<AppBarButton Icon="Sort" Label="Sort">
<AppBarButton.Flyout>
<MenuFlyout>
<MenuFlyoutSubItem Text="By name">
<MenuFlyoutItem Text="Asc">
<MenuFlyoutItem.Icon>
<FontIcon Glyph="" Visibility="{Binding CurrentSortOrder, Mode=OneWay, Converter={StaticResource TaskSortTypeToVisibilityConverter}, ConverterParameter={x:Bind localModels:TaskSortType.BY_NAME_ASC}}" />
</MenuFlyoutItem.Icon>
</MenuFlyoutItem>
<MenuFlyoutItem Text="Desc">
<MenuFlyoutItem.Icon>
<FontIcon Glyph="" Visibility="Collapsed" />
</MenuFlyoutItem.Icon>
</MenuFlyoutItem>
</MenuFlyoutSubItem>
</MenuFlyout>
</AppBarButton.Flyout>
</AppBarButton>
</Grid>
Converter:
public class TaskSortTypeToVisibilityConverter : IValueConverter
{
public Visibility OnTrue { get; set; }
public Visibility OnFalse { get; set; }
public TaskSortTypeToVisibilityConverter()
{
OnFalse = Visibility.Collapsed;
OnTrue = Visibility.Visible;
}
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value is null || parameter is null)
return Visibility.Collapsed;
var currentOrder = (TaskSortType)value;
var targetOrder = (TaskSortType)parameter;
return currentOrder == targetOrder ? OnTrue : OnFalse;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
if (value is Visibility == false)
return DependencyProperty.UnsetValue;
if ((Visibility)value == OnTrue)
return true;
else
return false;
}
}
Any help would be appreciated
Edit:
I get the exception here: this.InitializeComponent();
public sealed partial class MainPage : Page
{
public TestViewModel ViewModel { get; set; }
public MainPage()
{
ViewModel = new TestViewModel();
this.InitializeComponent();
}
}
Edit 2:
public enum TaskSortType
{
BY_NAME_ASC = 0,
BY_NAME_DESC = 1,
BY_UPDATED_DATE_ASC = 2,
BY_UPDATED_DATE_DESC = 3,
}
It seems that i cant use x:Bind directly in the ConverterParameter .. So i ended with the following:
I added in my page resources:
<localModels:TaskSortType x:Key="TaskSortByNameAsc">BY_NAME_ASC</localModels:TaskSortType>
<localModels:TaskSortType x:Key="TaskSortByNameDesc">BY_NAME_DESC</localModels:TaskSortType>
<localModels:TaskSortType x:Key="TaskSortByUpdatedDateAsc">BY_UPDATED_DATE_ASC</localModels:TaskSortType>
<localModels:TaskSortType x:Key="TaskSortByUpdatedDateDesc">BY_UPDATED_DATE_DESC</localModels:TaskSortType>
And then i replaced the ConverterParameter binding with the following:
<FontIcon Glyph="" Visibility="{Binding CurrentSortOrder, Mode=OneWay, Converter={StaticResource TaskSortTypeToVisibilityConverter}, ConverterParameter={StaticResource BY_NAME_ASC}}" />
Another workaround would be to pass the corresponding value in the ConverterParameter, for example ConverterParameter=0 or ConverterParameter="BY_NAME_ASC"and the cast that parameter to the corresponding enum value

C# SolidColorBrush to my Converter Class

i have an object of the type SolidColorBrush and it holds
a SolidColorBrush.
Now i have a converter for my dataGrid which is binded to a list.
Each row in this dataGrid will be colored by the Converter i have.
All is working fine, but how can i return my SolidColorBrush object instead of an static "Brushes.Red" for example.
My converter:
[ValueConversion(typeof(MainWindow.eErrorLevel), typeof(Brush))]
public class TypeToColourConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
MainWindow.eErrorLevel errorLevel = (MainWindow.eErrorLevel)value;
switch (errorLevel)
{
case MainWindow.eErrorLevel.Information:
return Brushes.Red;
case MainWindow.eErrorLevel.Warning:
return Brushes.Yellow;
case MainWindow.eErrorLevel.Error:
return Brushes.Red;
}
return Brushes.Gray;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
#endregion
}
My converter is not in the MainWindow, if thats important
And My SolidColorBrush object in my MainWindow which is public:
public CurrentColor CurrentColors = new CurrentColor();
public class CurrentColor
{
public SolidColorBrush ERROR { get; set; }
public SolidColorBrush WARNING { get; set; }
public SolidColorBrush INFORMATION { get; set; }
}
EDIT: my brushes can be dynamically set by the user itself
EDIT2: now its working thanks guys :)
Assuming that these colours won't change at runtime, you could declare your brushes as resources above your converter and add properties to your converter for each brush as follows:
Amend your converter to:
[ValueConversion(typeof(MainWindow.eErrorLevel), typeof(Brush))]
public class TypeToColourConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
MainWindow.eErrorLevel errorLevel = (MainWindow.eErrorLevel)value;
switch (errorLevel)
{
case MainWindow.eErrorLevel.Information:
return Error;
case MainWindow.eErrorLevel.Warning:
return Warning;
case MainWindow.eErrorLevel.Error:
return Information;
}
return Normal;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
#endregion
public Brush Normal { get; set; }
public Brush Error { get; set; }
public Brush Warning { get; set; }
public Brush Information { get; set; }
}
Amend your XAML (wherever your converter is added):
<SolidColorBrush x:Key="Normal" Color="#FFAAAAAA"/>
<SolidColorBrush x:Key="Error" Color="#FFFF0000"/>
<SolidColorBrush x:Key="Warning" Color="#FF00FF00"/>
<SolidColorBrush x:Key="Information" Color="#FF0000FF"/>
<local:TypeToColourConverter x:Key="TypeToColourConverter" Normal="{StaticResource Normal}" Error="{StaticResource Error}" Warning="{StaticResource Warning}" Information="{StaticResource Information}" />
This is very 'designer-friendly' (i.e. all these colours can then be changed in Blend) and easy to maintain.
Hope it helps.
Like I said in my comments, here's an example, passing it as converterparameter, there are probably alternatives:
XAML
<Window x:Class="WpfApplicationTestColorConverter.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:WpfApplicationTestColorConverter"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:ErrorColors x:Key="Colors" />
<local:TypeToColourConverter x:Key="ColorConverter" />
</Window.Resources>
<Grid>
<ListBox x:Name="ListBox1" ItemsSource="{Binding MyObjects}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock
Text="{Binding Title}"
Background="{Binding ErrorLevel,
Converter={StaticResource ColorConverter},
ConverterParameter={StaticResource Colors}}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
Code behide
public partial class MainWindow : Window
{
public ObservableCollection<MyObject> MyObjects { get; } = new ObservableCollection<MyObject>();
public MainWindow()
{
InitializeComponent();
DataContext = this;
// find the (static)resource
var colors = (ErrorColors)FindResource("Colors");
colors.ERROR = new SolidColorBrush(Colors.Red);
colors.WARNING = new SolidColorBrush(Colors.Orange);
colors.INFORMATION = new SolidColorBrush(Colors.Lime);
// Add objects to the list
MyObjects.Add(new MyObject { Title = "This is an error", ErrorLevel = ErrorLevel.Error });
MyObjects.Add(new MyObject { Title = "This is a warning", ErrorLevel = ErrorLevel.Warning });
MyObjects.Add(new MyObject { Title = "This is information", ErrorLevel = ErrorLevel.Information });
}
}
The Converter
[ValueConversion(typeof(ErrorLevel), typeof(Brush))]
public class TypeToColourConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
if (!(value is ErrorLevel))
return Brushes.Gray;
if (!(parameter is ErrorColors))
return Brushes.Gray;
var lvl = (ErrorLevel)value;
var currentColor = (ErrorColors)parameter;
switch (lvl)
{
case ErrorLevel.Information:
return currentColor.INFORMATION;
case ErrorLevel.Warning:
return currentColor.WARNING;
case ErrorLevel.Error:
return currentColor.ERROR;
}
return Brushes.Gray;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
#endregion
}
public class ErrorColors
{
public SolidColorBrush ERROR { get; set; }
public SolidColorBrush WARNING { get; set; }
public SolidColorBrush INFORMATION { get; set; }
}
public enum ErrorLevel
{
Error,
Warning,
Information
}
public class MyObject
{
public string Title { get; set; }
public ErrorLevel ErrorLevel { get; set; }
}
Results:

Converter from class property

I want to do Binding to specific property, and make the checkbox converter according to the property values in class.
I have an error.
This is my class:
namespace WpfApplication2
{
class Point
{
public int point { get; set; }
public Point(int x)
{
this.point = x;
}
}
}
This is my Converter:
namespace WpfApplication2
{
public class NumberToCheckedConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if ((int)parameter >= 5)
return true;
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
}
This is my CS window's code:
namespace WpfApplication2
public partial class MainWindow : Window
{
List<Point> points;
public MainWindow()
{
InitializeComponent();
points = new List<Point>();
Random rnd = new Random();
for (int i = 0; i < 10; i++)
{
points.Add(new Point(rnd.Next()));
}
this.DataContext = points;
}
}
}
And this is the xaml:
Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication2"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:NumberToCheckedConverter x:Key="NumberToCheckedConverter"></local:NumberToCheckedConverter>
<DataTemplate x:Key="MyDataTemplate"
DataType="local:MyData">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="70" />
<ColumnDefinition Width="70" />
</Grid.ColumnDefinitions>
<TextBox Text="Over 5" />
<CheckBox Grid.Column="1" IsChecked="{Binding point, Converter={StaticResource NumberToCheckedConverter}, ConverterParameter=point}" IsEnabled="False" />
</Grid>
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox ItemTemplate="{StaticResource MyDataTemplate}" ItemsSource="{Binding}" Height="172" HorizontalAlignment="Left" Margin="0,51,-0.2,0" Name="listBox1" VerticalAlignment="Top" Width="517" >
</ListBox>
</Grid>
I have an error with the converter. What's wrong here?
A ConverterParameter is not a binding, so writing:
IsChecked="{Binding point, Converter={StaticResource NumberToCheckedConverter}, ConverterParameter=point}"
Is setting parameter to "point"; not really what you want. As it turns out, Converter Parameters aren't even Dependency Properties, and so cannot be bound.
However, you don't even need the parameter; just change your code to:
public class NumberToCheckedConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if ((int)value >= 5)
return true;
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return Binding.DoNothing; //Null would cause an error on a set back.
}
}
Converting the value will do what you want. If you wanted the threshold to be configurable, that is where ConverterParamater would come into play.

problem for bind radiobutton to database

Please following my code :
<Grid DataContext="{Binding ElementName=dataGrid_services, Path=SelectedItem}"
Width="766">
<RadioButton Content="visit" IsChecked="{Binding Path=type_services}"
FontFamily="Tahoma"/>
i want to bind ischecked property from radiobutton but return value is not false or true.
the value is string. please help me how to bind this value?
thanks in advance
Use an IValueConverter.
Given this window containing your radiobutton and associated bindings:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525" x:Name="dataGrid_services">
<Window.Resources>
<local:CheckedConverter x:Key="converter"/>
</Window.Resources>
<Grid DataContext="{Binding ElementName=dataGrid_services, Path=SelectedItem}" Width="766">
<RadioButton Content="visit" IsChecked="{Binding Path=type_services, Converter={StaticResource converter}}" FontFamily="Tahoma"/>
</Grid>
The changes are adding a namespace reference for local (or whichever namespace your converter is in):
xmlns:local="clr-namespace:WpfApplication1"
creating the converter resource:
<Window.Resources>
<local:CheckedConverter x:Key="converter"/>
</Window.Resources>
and using the converter resource:
IsChecked="{Binding Path=type_services, Converter={StaticResource converter}}"
The converter looks like this and simply converts from string to boolean.
public class CheckedConverter : System.Windows.Data.IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string typeService = value as string;
if (typeService == "Yes it is")
{
return true;
}
if (typeService == "Nope")
{
return false;
}
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
bool typeService = (bool)value;
if (typeService)
{
return "Yes it is";
}
else
{
return "Nope";
}
}
}
You'll have to define a value converter to convert from string to boolean and use it with your RadioButton.
public class StringToBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
return Convert.ToBool(value);
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return Convert.ToString(value);
}
}
and in XAML, use
<RadioButton Content="visit" IsChecked="{Binding Path=type_services, Converter={StaticResource stringToBoolConverter}}"
FontFamily="Tahoma"/>
where stringToBoolConverter is defined in the resources of a parent element.
<Window.Resources>
<local:StringToBoolConverter x:Key="stringToBoolConverter" />
</Window.Resources>

Categories