problem for bind radiobutton to database - c#

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>

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;
}

XAML, C# : How to Set ListView Visibility to Collapse/Visible on Checkbox value toggle?

i am newbie in C# and Windows app development, just for learning purpose i am trying to build a Windows 10 universal app. I am experimenting with Hub view.
Below is the Xaml structure of my file.
<Hub>
<HubSection1>
//SomeData here
</HubSection1>
<HubSection2>
<DataTemplate>
<Grid>
<ListView1>
<CheckBox1>
<ListView2>
//SomeData here
<CheckBox2>
<ListView3>
//SomeData here
<CheckBox3>
<ListView4>
//SomeData here
</ListView1>
</Grid>
</DataTemplate>
</HubSection2>
<HubSection3>
//SomeData here
</HubSection3>
<HubSection4>
//SomeData here
</HubSection4>
</Hub>
So what i am trying to do is to toggle the visibility of ListView(2,3,4) Using Checkboxes(1,2,3) respectively. But in my c# sharp code i am unable to access the variables defined in my XAML file, i tried FindName() in checkbox listeners Method but it didn't helped. is there any way i can fetch data or variables or bind them ??
Use converter concept:
public class BooleanToVisibility : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool isChecked = false;
if (bool.TryParse(value.ToString(), out isChecked))
{
return isChecked ? Visibility.Visible : Visibility.Collapsed;
}
return visibility;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}
XAML:
<Window x:Class="MyApp.Windows.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:converters="clr-namespace:MyApp.Converters">
<StackPanel>
<StackPanel.Resources>
<converters:BooleanToVisibility x:Key="boolToVisibility"/>
</StackPanel.Resources>
<CheckBox Content="Check to see ListView" Name="changeVisibility"/>
<ListView Visibility="{Binding Path=IsChecked, ElementName=changeVisibility, Converter={StaticResource boolToVisibility}}"/>
</StackPanel>
</Window>

WPF boolean column checkbox

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();
}
}

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.

XAML doesn't see my IValueConverter class

I'm creating a simple WP8, but I'm having troubles hiding (changing the Visibility property) on a control.
In XAML I've added xmlns:local="clr-namespace:MyProjectName" (I've also tried with using).
The XAML is then structured as follows:
<phone:PhoneApplicationPage
x:Class="MyProjectName.Pages.Main"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MyProjectName"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d"
shell:SystemTray.IsVisible="True" Margin="0,4,0,-4" Background="#FFBD3F3F">
<Grid x:Name="LayoutRoot" Background="{StaticResource PhoneBackgroundBrush}" >
<Grid x:Name="ContentPanel" Grid.Row="1" >
<Grid.Resources>
<local:VisibilityFormatter x:Key="FormatConverter" />
</Grid.Resources>
<phone:LongListSelector Grid.Row="4">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Obj}"
Visibility="{Binding ObjVisibility,
Mode=OneWay,
Converter={StaticResource FormatConverter}}" />
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</Grid>
</Grid>
The problem is at the <local:...> line: The name "VisibilityFormatter" does not exist in the namespace "clr-namespace:MyProjectName".
The class is defined as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
namespace MyProjectName
{
public class Formatter
{
public class VisibilityFormatter : IValueConverter
{
// Retrieve the format string and use it to format the value.
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var visibility = parameter as bool?;
return visibility.HasValue && visibility.Value ? Visibility.Visible : Visibility.Collapsed;
}
// No need to implement converting back on a one-way binding
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
}
The class ObjInfo is a simple public class with two properties:
namespace MyProjectName.Models
{
public class ObjInfo
{
public bool ObjVisibility { get; set; }
public string Obj { get; set; }
}
}
It's similar to this question, but no migrating is involved. I'm developing on WP8 from the get-go.
What am I trying to achieve? Well. I'm storing whether the control should be visible or not in that bool property. Since the XAML control's property only grokks the Visibility enum, but not bool, I need to convert it to that enum.
The VisibilityFormatter is an inner class of the Formatter class. You don't really need the Formatter class, just make the VisibilityFormatter a top class, and the XAML parser will find it.
Also, the general naming convention for converters is XXXConverter and not XXXFormatter, but that's no rule.
You don't have MyProjectName.VisibilityFormatter in your project, you have
MyProjectName.Formatter.VisibilityFormatter
You should remove Formatter class and leave only:
namespace MyProjectName
{
public class VisibilityFormatter : IValueConverter
{
// Retrieve the format string and use it to format the value.
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var visibility = parameter as bool?;
return visibility.HasValue && visibility.Value ? Visibility.Visible : Visibility.Collapsed;
}
// No need to implement converting back on a one-way binding
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}

Categories