WPF boolean column checkbox - c#

I want to change the boolean checkbox of the "EstBonClient" cell in my Datagrid to a specific color. If the checkbox is checked the background color of the cell will be green and if the checkbox is not check the background color of the cell will be red. I want that the checkbox is not in the Datagrid.
Thank you guys !

Xaml:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:local="clr-namespace:WpfApplication1"
>
<Window.DataContext>
<local:MyViewModel/>
</Window.DataContext>
<Window.Resources>
<local:BooleanToTextConverter x:Key="booleanToTextConverter" />
<local:BoolToColorConverter x:Key="booleanToColorConverter" />
</Window.Resources>
<Grid>
<StackPanel Background="{Binding Path=IsChecked, Converter={StaticResource booleanToColorConverter}}">
<CheckBox IsChecked="{Binding Path=IsChecked}" Grid.Column="0">Check Me!</CheckBox>
<TextBlock FontSize="30" HorizontalAlignment="Center" Text="{Binding IsChecked, Converter={StaticResource booleanToTextConverter}}" />
</StackPanel>
</Grid>
C#:
ViewModel:
public class MyViewModel : INotifyPropertyChanged
{
bool _isChecked;
public bool IsChecked
{
get { return _isChecked; }
set {
_isChecked = value;
OnPropertyChanged("IsChecked");
}
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
Converters:
public class BooleanToTextConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return (bool)value ? "Est Bon Client" : "Est Mauvais Client";
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class BoolToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return (bool)value ? new SolidColorBrush(Colors.GreenYellow) : new SolidColorBrush(Colors.DarkRed);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}

Related

Custom TextBox user control implementing a converter in WPF

I am trying to build a custom user control, specifically a custom TextBox that converts the text entered by the user to uppercase as it is typed and displays it in the control. However, I cannot get this to work. Here is my code:
CustomTextBox UserControl:
<UserControl x:Class="SOFWpf.CustomTextBox"
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:converters="clr-namespace:SOFWpf.Converters"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<converters:CaseConverter x:Key="CaseConverter" />
</UserControl.Resources>
<TextBox Text="{Binding Path=., Converter={StaticResource CaseConverter}}"/>
UserControl's Code-Behind:
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(CustomTextBox), new UIPropertyMetadata(""));
Usage:
<local:CustomTextBox Text="a b c"/>
Converter:
public class CaseConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string text = value as string;
return text?.ToUpper();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string text = value as string;
return text?.ToLower();
}
}
What do I need to change to make this custom TextBox work as intended?
You need to add binding Path=Text:
<TextBox Text="{Binding Path=Text, Converter={StaticResource CaseConverter}}"/>
And in the user control constructor set DataContext to this:
public CustomTextBox()
{
InitializeComponent();
DataContext = this;
}

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.

NullToVisibilityConverter make visible if not null

Want to hide and show property grid for SelectedItem in listview
<UserControl xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
<ListView>
<!--here is list view-->
</ListView>
<xctk:PropertyGrid SelectedObject="{Binding Active}" Visibility="{Binding Active, Converter=NullToVisibilityConverter}" >
</xctk:PropertyGrid>
</UserControl>
So I need converter and use it in visibility property converter. Any help?
public class NullVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value == null ? Visibility.Hidden : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Then reference the NullVisibilityConverter in your XAML Resources.
<StackPanel.Resources>
<simpleXamlContent:NullVisibilityConverter x:Key="NullToVisibilityConverter"/>
</StackPanel.Resources>
To use the converter we can create one in the resources, and refer to it as a static resource in the binding statement.
<UserControl xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit">
<UserControl.Resources>
<yournamespace:NullVisibilityConverter x:Key="NullToVisibilityConverter"/>
</UserControl.Resources>
<ListView>
<!--here is list view-->
</ListView>
<xctk:PropertyGrid SelectedObject="{Binding Active}" Visibility="{Binding Active, Converter={StaticResource NullToVisibilityConverter}}" >
</xctk:PropertyGrid>
</UserControl>
and Converter class itself
public class NullVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value == null ? Visibility.Hidden : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
There is little more useful version allows to set default invisibility value:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string defaultInvisibility = parameter as string;
Visibility invisibility = (defaultInvisibility != null) ?
(Visibility)Enum.Parse(typeof(Visibility), defaultInvisibility)
: Visibility.Collapsed;
return value == null ? invisibility : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
Where ever in resources add:
<converters:NullReferenceToVisibilityConverter x:Key="NullToVis" />
And use it like there:
<StackPanel Visibility="{Binding MyObject, Converter={StaticResource NullToVis}}">
<StackPanel Visibility="{Binding MyObject, Converter={StaticResource NullToVis}, ConverterParameter=Hidden}">

How to Implement a BoolToVisibilityConverter

In my app I would like to toggle the visibility of an item in a StackPanel. My Stackpanel contains an Image and a TextBlock. How would I properly use a BoolToVisibilityConverter to toggle the visibility of the TextBlock, and save this setting for the users benefit?
Currently what I have is as follows, although I am getting a few errors. Important note, I need to use an ApplicationBar menu item as the click event that drives the toggling of the TextBox visibility.
EDIT
Error no longer occurring although the visibility of the TextBlock is not changing.
XAML
xmlns:common="clr-namespace:TestApp.Common"
<phone:PhoneApplicationPage.Resources>
<common:BooleanToVisibilityConverter x:Key="BoolToVisConv" />
</phone:PhoneApplicationPage.Resources>
<ListBox Name="ListBoxEffects" SelectionMode="Single" ItemsSource="{Binding}" Margin="{Binding}"
toolkit:TiltEffect.IsTiltEnabled="True" SelectionChanged="ListBox_SelectionChanged"
ItemContainerStyle="{StaticResource ListBoxItemStyle1}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<toolkit:WrapPanel ItemWidth="159" ItemHeight="Auto" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical" >
<Image Source="{Binding Thumbnail}" Width="155" Height="155" />
<TextBlock Text="{Binding Name}" Visibility="{Binding IsTextBlockVisible, Converter={StaticResource BoolToVisConv}}" TextWrapping="Wrap" FontSize="{StaticResource PhoneFontSizeNormal}" VerticalAlignment="Center" HorizontalAlignment="Center" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Code Behind
private void BuildLocalizedApplicationBar()
{
ApplicationBar = new ApplicationBar();
ApplicationBarMenuItem showFilterNamesMenuItem = new ApplicationBarMenuItem();
if (Settings.ShowFilterNames.Value)
showFilterNamesMenuItem.Text = AppResources.EditPage_EffectNames_Hide;
else
showFilterNamesMenuItem.Text = AppResources.EditPage_EffectNames_Show;
showFilterNamesMenuItem.Click += showFilterNamesMenuItem_Click;
ApplicationBar.MenuItems.Add(showFilterNamesMenuItem);
}
void showFilterNamesMenuItem_Click(object sender, EventArgs e)
{
if(Settings.ShowFilterNames.Value)
{
((ApplicationBarMenuItem)ApplicationBar.MenuItems[0]).Text = AppResources.EditPage_EffectNames_Hide;
Settings.ShowFilterNames.Value = false;
//Toggle the text block visibility to here
}
else
{
((ApplicationBarMenuItem)ApplicationBar.MenuItems[0]).Text = AppResources.EditPage_EffectNames_Show;
Settings.ShowFilterNames.Value = true;
//Toggle the text block visibility to here
}
}
A class for the BooleanToVisibilityConverter
//Error on BooleanToVisibilityConverter stating does not implement interface member 'System.Windows.Data.IValueConverter.Convert(object, System.Type, object, System.Globalization.CultureInfo)
public class BooleanToVisibilityConverter : IValueConverter
{
public class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo language)
{
return (value is bool && (bool)value) ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo language)
{
return value is Visibility && (Visibility)value == Visibility.Visible;
}
}
Try this:
public class BooleanToVisibilityConverter : IValueConverter
{
private object GetVisibility(object value)
{
if (!(value is bool))
return Visibility.Collapsed;
bool objValue = (bool)value;
if (objValue)
{
return Visibility.Visible;
}
return Visibility.Collapsed;
}
public object Convert(object value, Type targetType, object parameter, string language)
{
return GetVisibility(value);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
Here is mine:
public class BoolToVisConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return (value is bool && (bool)value) ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return value is Visibility && (Visibility)value == Visibility.Visible;
}
}
There is already an implemenation of the converter: http://msdn.microsoft.com/en-us/library/system.windows.controls.booleantovisibilityconverter(v=vs.110).aspx

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