I want to disable some items of combobox by specific conditions. For this issue, I used multibinding.
If I described all items of combobox in xaml, there is no problem. But I want to populate combobox items programmatically. So in this case , I could not get items, returns null, and throw me out of the program in the first step.
my xaml codes are like that:
<Window.Resources>
<local:TekerDisabler x:Key="tekerDisabler"/>
</Window.Resources>
<Grid>
<ComboBox x:Name="cbx" HorizontalAlignment="Left" Margin="41,125,0,0" VerticalAlignment="Top" Width="227">
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Setter Property="IsEnabled">
<Setter.Value>
<MultiBinding Converter="{StaticResource tekerDisabler}">
<Binding ElementName="txt1" Path="Text"/>
<Binding ElementName="txt2" Path="Text"/>
<Binding ElementName="txt3" Path="Text"/>
<Binding RelativeSource="{RelativeSource Self}"/>
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
<TextBox x:Name="txt1" HorizontalAlignment="Left" Height="23" Margin="41,38,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="txt2" HorizontalAlignment="Left" Height="23" Margin="207,38,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="211" TextChanged="txt2_TextChanged"/>
<TextBox x:Name="txt3" HorizontalAlignment="Left" Height="24" Margin="478,37,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="196"/>
</Grid>
and my c# codes are like that:
namespace App1.Pencereler
{
public partial class deneme : Window
{
public deneme()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
cbx.Items.Add("0");
cbx.Items.Add("1");
cbx.Items.Add("2");
cbx.Items.Add("3");
}
private void txt2_TextChanged(object sender, TextChangedEventArgs e)
{
cbx.SelectedIndex = 1;
}
}
class TekerDisabler : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
bool enable = true;
var itemler = values[3] as ComboBoxItem;
if (itemler == null || values[0].ToString() == null || values[1].ToString() == null || values[2].ToString() == null)
{ enable = true; }
else
{
switch (values[0].ToString())
{
case "a":
switch (values[1].ToString())
{
case "b":
switch (values[2].ToString())
{
case "c":
switch (itemler.Content.ToString())
{
case "0":
case "2":
enable = false;
break;
default:
enable = true;
break;
}
break;
default:
enable = true;
break;
}
break;
default:
enable = true;
break;
}
break;
default:
enable = true;
break;
}
}
return enable;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
For Example, in the first step, I write txt1:a, txt2:b, txt3:d and so all items' display enabled, and then I write txt1:a, txt2:b, txt3:c and contents of combobox (0,2) disabled, there is no problem. But when running program, in the first step I write txt1:a, txt2:b, txt3:c when drop down combobox, program trow me out.
How to overcome this problem?
Error Message and details are like that:
And Error details are like that:
System.NullReferenceException
HResult=0x80004003
İleti=Nesne başvurusu bir nesnenin örneğine ayarlanmadı.
Kaynak=App1
StackTrace:
konum App1.Pencereler.TekerDisabler.Convert(Object[] values, Type targetType, Object parameter, CultureInfo culture) D:\C Sharp\WPF\App1\App1\Pencereler\deneme.xaml.cs içinde: 60. satır
konum System.Windows.Data.MultiBindingExpression.TransferValue()
konum System.Windows.Data.MultiBindingExpression.Transfer()
konum System.Windows.Data.MultiBindingExpression.UpdateTarget(Boolean includeInnerBindings)
konum System.Windows.Data.MultiBindingExpression.AttachToContext(Boolean lastChance)
konum System.Windows.Data.MultiBindingExpression.AttachOverride(DependencyObject d, DependencyProperty dp)
konum System.Windows.Data.BindingExpressionBase.OnAttach(DependencyObject d, DependencyProperty dp)
It would be interesting to know what exact error you get.
I assume the ComboBoxItem.Content returns null. The item containers are rendered (generated) after the ComboBox is opened. Only the data items exist at this moment. So opening the drop down the first time all item containers are null and about to be rendered.
Anyway, the following simplified version of your code will very likely fix your problem:
TekerDisabler.cs
public class TekerDisabler : IMultiValueConverter
{
#region Implementation of IMultiValueConverter
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var currentItem = values[0] as string;
var predicate = "abc";
string input = string.Concat(values.Skip(1).Cast<string>());
return !(input.Equals(predicate, StringComparison.Ordinal)
&& (currentItem.Equals("0", StringComparison.Ordinal)
|| currentItem.Equals("2", StringComparison.Ordinal)));
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) =>
throw new NotSupportedException();
#endregion
}
TekerDisabler.cs - Alternative version
public class TekerDisabler : IMultiValueConverter
{
#region Implementation of IMultiValueConverter
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var currentItem = values[0] as string;
var predicate = "abc";
string input = string.Concat(values.Skip(1).Cast<string>());
return !(values[1].Equals("a", StringComparison.Ordinal)
&& values[2].Equals("b", StringComparison.Ordinal)
&& values[3].Equals("c", StringComparison.Ordinal)
&& (currentItem.Equals("0", StringComparison.Ordinal)
|| currentItem.Equals("2", StringComparison.Ordinal)));
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) =>
throw new NotSupportedException();
#endregion
}
MainWindow.xamlk.cs
partial class MainWIndow : Window
{
public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register(
"Items",
typeof(ObservableCollection<string>),
typeof(MainWindow),
new PropertyMetadata(default(ObservableCollection<string>)));
public ObservableCollection<string> Items
{
get => (ObservableCollection<string>) GetValue(MainWindow.ResultsProperty);
set => SetValue(MainWindow.ResultsProperty, value);
}
}
MainWindow.xaml
<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=main:MainWindow}, Path=Items}">
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Setter Property="IsEnabled">
<Setter.Value>
<MultiBinding Converter="{StaticResource CellForegroundMultiValueConverter}">
<Binding />
<Binding ElementName="TextBox1" Path="Text" />
<Binding ElementName="TextBox2" Path="Text" />
<Binding ElementName="TextBox3" Path="Text" />
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
<TextBox x:Name="TextBox1" />
<TextBox x:Name="TextBox2" />
<TextBox x:Name="TextBox3" />
I accomlished to overcome my problem by adding
cbx.IsDropDownOpen = true;
cbx.IsDropDownOpen = false;
after
cbx.Items.Add("0");
cbx.Items.Add("1");
cbx.Items.Add("2");
cbx.Items.Add("3");
in 'Window_Loaded' event.
I'm newbie on WPF. I didn't success to set selected index\selected value to list box of images items.
My current code is:
On xaml:
<ListBox Name="symbolSrc" Grid.Row="1" Width="485" Height="100" HorizontalAlignment="Left" Margin="7,-35,0,0" ItemTemplate="{StaticResource cmbTemplate}" IsSynchronizedWithCurrentItem="True" SelectedValuePath="photo">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Padding" Value="6 0 0 0" />
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemsSource>
<MultiBinding Converter="{StaticResource SymbolComboboxItemsFilter}">
<Binding ElementName ="RadioButLR" Path="IsChecked" Mode="OneWay"/>
<Binding ElementName ="RadioButHR" Path="IsChecked" Mode="OneWay"/>
</MultiBinding>
</ListBox.ItemsSource>
<ListBox.SelectedValue>
<MultiBinding Converter="{StaticResource SymbolComboboxSelectedItem}">
<Binding ElementName ="RadioButLR" Path="IsChecked" Mode="OneWay"/>
<Binding ElementName ="RadioButHR" Path="IsChecked" Mode="OneWay"/>
</MultiBinding>
</ListBox.SelectedValue>
</ListBox>
On xaml.cs:
public class SymbolComboboxItemsFilterConverter: IMultiValueConverter
{
public class symbolCmbBoxItem
{
public string photo { get; set; }
public string photoName { get; set; }
}
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
List<symbolCmbBoxItem> itemsList = new List<symbolCmbBoxItem>();
string targetDir = System.Windows.Forms.Application.ExecutablePath + "\\..\\..\\..\\INIT\\IC";
string[] filesArray = Directory.GetFiles(targetDir, "*", SearchOption.TopDirectoryOnly);
if ((bool)values[0])
{
foreach (string file in filesArray.Where(s => s.Contains("_LR")))
{
itemsList.Add(new symbolCmbBoxItem { photo = file, photoName = "" });
}
}
else
{
foreach (string file in filesArray.Where(s => s.Contains("_HR")))
{
itemsList.Add(new symbolCmbBoxItem { photo = file, photoName = "" });
}
}
return itemsList;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class SymbolComboboxItemsSelectedIndex : IMultiValueConverter
{
public class symbolCmbBoxItem
{
public string photo { get; set; }
public string photoName { get; set; }
}
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
List<symbolCmbBoxItem> itemsList = new List<symbolCmbBoxItem>();
string targetDir = System.Windows.Forms.Application.ExecutablePath + "\\..\\..\\..\\INIT\\IC";
string[] filesArray = Directory.GetFiles(targetDir, "*", SearchOption.TopDirectoryOnly);
if ((bool)values[0])
{
string item = filesArray.Where(s => s.Contains("_LR")).First();
return new symbolCmbBoxItem { photo = item, photoName = "" };
}
else
{
string item = filesArray.Where(s => s.Contains("_HR")).First();
return new symbolCmbBoxItem { photo = item, photoName = "" };
}
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
I also tried set the selected item by using:
SelectedItem="1"
And it didn't work.
Also tried to using the same multi converter at above and set always the selected item to "1" and it also didn't work.
(In order to set listbox of images I used by below reference:
http://www.codescratcher.com/wpf/wpf-combobox-with-image/ )
Any ideas please?
Your help is very appreciated!
I would like to display "Yes" or "No" for whenever a Boolean type data received(it can receive different types of data) for generating a column in RadGridView instead of a checkbox. I would like to implement this changes in xaml. Columns are generating dynamically. This is how it's created now:
<telerik:RadGridView x:Name="Data" Grid.Row="3" Margin="5" AutoGenerateColumns="False" CanUserSortColumns="True" IsFilteringAllowed="True"
grid:RadGridViewColumnsBinding.ColumnsCollection="{Binding Path=ColumnsData}"
IsReadOnly="False" CanUserResizeColumns="True"/>
I am new in Silverlight coding. Will really appreciate if someone can help.
You should check out Telerik's ConditionalDataTemplateSelector they have in this demo, and read about IValueConverter if you haven't already.
Depending on what you are trying to do with all your columns, the ConditionalDataTemplateSelector might be overkill, but you can use it to create a rule system for what DataTemplate to use for a given cell based on a custom rule system.
<Grid.Resources>
...
<DataTemplate x:Key="CellDisplayTextBox">
<TextBlock Text="{Binding Value, Converter={StaticResource BooleanToYesNoConverter}}" />
</DataTemplate>
<selector:ConditionalDataTemplateSelector x:Key="displaySelector" ConditionConverter="{StaticResource someConverter}">
<selector:ConditionalDataTemplateSelector.Rules>
<selector:ConditionalDataTemplateRule DataTemplate="{StaticResource CellDisplayTextBox}">
<selector:ConditionalDataTemplateRule.Value>
<sys:Int32>1</sys:Int32> <!--You need to figure out what value and type to use here -->
</selector:ConditionalDataTemplateRule.Value>
</selector:ConditionalDataTemplateRule>
...
</selector:ConditionalDataTemplateSelector.Rules>
</Grid.Resources>
...
<telerikGridView:RadGridView>
<telerik:RadGridView.Columns>
<telerik:GridViewDataColumn CellTemplateSelector="{StaticResource displaySelector}" CellEditTemplateSelector="{StaticResource editSelector}" />
</telerik:RadGridView.Columns>
</telerikGridView:RadGridView>
The IValueConverter will let you bind a bool value, but display a string value. For a BooleanToYesNoConverter you could do something like:
public class BooleanToYesNoConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool? bValue = value as bool?;
if (bValue.HasValue)
return bValue.Value ? "Yes" : "No";
else
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
string sValue = value as string;
return sValue == "Yes";
}
}
The ConditionalDataTemplateSelector code from the demo:
public class ConditionalDataTemplateSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
object conditionValue = this.ConditionConverter.Convert(item, null, null, null);
foreach (ConditionalDataTemplateRule rule in this.Rules)
{
if (Equals(rule.Value, conditionValue))
{
return rule.DataTemplate;
}
}
return base.SelectTemplate(item, container);
}
List<ConditionalDataTemplateRule> _Rules;
public List<ConditionalDataTemplateRule> Rules
{
get
{
if (this._Rules == null)
{
this._Rules = new List<ConditionalDataTemplateRule>();
}
return this._Rules;
}
}
IValueConverter _ConditionConverter;
public IValueConverter ConditionConverter
{
get
{
return this._ConditionConverter;
}
set
{
this._ConditionConverter = value;
}
}
}
public class ConditionalDataTemplateRule
{
object _Value;
public object Value
{
get
{
return this._Value;
}
set
{
this._Value = value;
}
}
DataTemplate _DataTemplate;
public DataTemplate DataTemplate
{
get
{
return this._DataTemplate;
}
set
{
this._DataTemplate = value;
}
}
}
I want to create a TextBox that can take measurement and convert it to different units if necessary (the end result being of type double). The conversion will be controlled by a value IsMetric. If IsMetric == true then "36.5 in" would turn into 927.1 (a double representing millimeters). Conversely, if IsMetric == false then "927.1 mm" would turn into 36.5.
I thought to use an IValueConverter on a regular TextBox, but the ConverterParameter is not a DependencyProperty and therefore I can't bind IsMetric to it.
I tried IMultiValueConverter but the ConvertBack function only receives the current value of the TextBox and not all the bound values. This means I don't know IsMetric when converting the user input.
Have I missed something with the ConvertBack function? If not, then do I need to create a class derived from TextBox?
You could use two converters one to convert from Metric and another to Metric:
public class ToMetricConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return "(metric) value";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class FromMetricConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return "(Inch) value";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
And use a DataTrigger in the UI to select the appropriate converter based on that bool value:
<Window.Resources>
<wpfApplication13:ToMetricConverter x:Key="ToMetricConverter"/>
<wpfApplication13:FromMetricConverter x:Key="FromMetricConverter"/>
</Window.Resources>
<Grid>
<StackPanel>
<CheckBox IsChecked="{Binding IsMetric,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></CheckBox>
<TextBox >
<TextBox.Style>
<Style TargetType="TextBox">
<Style.Triggers>
<DataTrigger Binding="{Binding IsMetric,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Value="True">
<Setter Property="Text" Value="{Binding Val,Converter={StaticResource ToMetricConverter}}"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding IsMetric,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Value="False">
<Setter Property="Text" Value="{Binding Val,Converter={StaticResource FromMetricConverter}}"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
</StackPanel>
</Grid>
If thats the only thing you want to do, try other way to use converter parameter.
But, and i would have choose this option - if your textbox has more logics in it, or tend to have more dependecie - Create custom control that inherits from textbox, and add your own dependecy properties. Then you can use your IsMetric and convert it as you want on propertychanged etc.
I ended up with something along these lines for now. Would still enjoy a solution that doesn't require a DataTrigger for every possible value.
It's a bit different than the answer posted by #SamTheDev but along the same lines.
xaml
<UserControl x:Class="MyNamespace.Controls.MeasurementTextBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:MyNamespace.Converters"
xmlns:b="clr-namespace:MyNamespace.Behaviors"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
x:Name="root">
<UserControl.Resources>
<c:MeasurementUnitConverter x:Key="muc"/>
<c:MeasurementConverter2 x:Key="mc"/>
<sys:Boolean x:Key="BooleanFalse">False</sys:Boolean>
<sys:Boolean x:Key="BooleanTrue">True</sys:Boolean>
</UserControl.Resources>
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="30"/>
</Grid.ColumnDefinitions>
<TextBox Margin="0" VerticalContentAlignment="Center" HorizontalAlignment="Stretch" HorizontalContentAlignment="Right" VerticalAlignment="Stretch"
b:AutoSelectBehavior.AutoSelect="True">
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<DataTrigger Binding="{Binding UseMetric, ElementName=root}" Value="True">
<Setter Property="Text" Value="{Binding Measurement, Mode=TwoWay, ElementName=root, Converter={StaticResource mc}, ConverterParameter={StaticResource BooleanTrue}}"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding UseMetric, ElementName=root}" Value="False">
<Setter Property="Text" Value="{Binding Measurement, Mode=TwoWay, ElementName=root, Converter={StaticResource mc}, ConverterParameter={StaticResource BooleanFalse}}"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
<!-- in or mm label -->
<Label VerticalAlignment="Center" Padding="0" Margin="5" HorizontalAlignment="Left" Grid.Column="1"
Content="{Binding UseMetric, ElementName=root, Converter={StaticResource muc}}"/>
</Grid>
</UserControl>
xaml.cs
using System;
using System.Windows;
using System.Windows.Controls;
namespace MyNamespace.Controls
{
/// <summary>
/// Interaction logic for MeasurementTextBox.xaml
/// </summary>
public partial class MeasurementTextBox : UserControl
{
public MeasurementTextBox()
{
// This call is required by the designer.
InitializeComponent();
}
public bool UseMetric {
get { return Convert.ToBoolean(GetValue(UseMetricProperty)); }
set { SetValue(UseMetricProperty, value); }
}
public static readonly DependencyProperty UseMetricProperty = DependencyProperty.Register("UseMetric", typeof(bool), typeof(MeasurementTextBox), new PropertyMetadata(MeasurementTextBox.UseMetricChanged));
private static void UseMetricChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
}
public double Measurement {
get { return (double)GetValue(MeasurementProperty); }
set { SetValue(MeasurementProperty, value); }
}
public static readonly DependencyProperty MeasurementProperty = DependencyProperty.Register("Measurement", typeof(double), typeof(MeasurementTextBox), new PropertyMetadata(MeasurementTextBox.MeasurementPropertyChanged));
private static void MeasurementPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
}
}
}
Converter
using System;
using System.Windows;
using System.Windows.Data;
namespace MyNamespace.Converters
{
class MeasurementConverter : IValueConverter
{
const double MILLIMETERS_IN_ONE_INCH = 25.4;
const string INCHES_ABBREVIATION = "in";
const string MILLIMETERS_ABBREVIATION = "mm";
const double ONE_THIRTY_SECOND = 0.03125;
const double ONE_SIXTEENTH = 0.0625;
const double ONE_EIGHTH = 0.125;
const double ONE_FOURTH = 0.25;
const double ONE_HALF = 0.5;
const double ONE = 1;
public double RoundToNearest(double value, int unitPrecision)
{
double fraction = 0;
int reciprocal = 0;
switch (unitPrecision)
{
case 0:
fraction = ONE;
reciprocal = (int)ONE;
break;
case 1:
fraction = ONE;
reciprocal = (int)ONE;
break;
case 2:
fraction = ONE_HALF;
reciprocal = (int)(1 / ONE_HALF);
break;
case 3:
fraction = ONE_FOURTH;
reciprocal = (int)(1 / ONE_FOURTH);
break;
case 4:
fraction = ONE_EIGHTH;
reciprocal = (int)(1 / ONE_EIGHTH);
break;
case 5:
fraction = ONE_SIXTEENTH;
reciprocal = (int)(1 / ONE_SIXTEENTH);
break;
case 6:
fraction = ONE_THIRTY_SECOND;
reciprocal = (int)(1 / ONE_THIRTY_SECOND);
break;
}
return Math.Round(value * reciprocal, MidpointRounding.AwayFromZero) * fraction;
}
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string strValue = (string)value;
bool isMetric = (bool)parameter;
double enteredValue = 0;
bool enteredValueIsImperial = false;
if (strValue.EndsWith(INCHES_ABBREVIATION))
{
enteredValueIsImperial = true;
strValue = strValue.Substring(0, strValue.Length - INCHES_ABBREVIATION.Length);
}
else if (strValue.EndsWith(MILLIMETERS_ABBREVIATION))
{
enteredValueIsImperial = false;
strValue = strValue.Substring(0, strValue.Length - MILLIMETERS_ABBREVIATION.Length);
}
else if (isMetric)
{
enteredValueIsImperial = false;
}
else
{
enteredValueIsImperial = true;
}
try
{
enteredValue = double.Parse(strValue);
}
catch (FormatException)
{
return DependencyProperty.UnsetValue;
}
if (isMetric)
{
if (enteredValueIsImperial)
{
//inches to mm
return RoundToNearest(enteredValue * MILLIMETERS_IN_ONE_INCH, 0);
//0 is mm
}
else
{
//mm to mm
return RoundToNearest(enteredValue, 0);
//0 is mm
}
}
else
{
if (enteredValueIsImperial)
{
//inches to inches
return RoundToNearest(enteredValue, 5);
}
else
{
//mm to inches
return RoundToNearest(enteredValue / MILLIMETERS_IN_ONE_INCH, 5);
}
}
}
}
}
Usage:
<mynamespace:MeasurementTextBox Measurement="{Binding SomeLength, Mode=TwoWay}"
UseMetric="{Binding IsMetric}"/>
I've got an enum like this:
public enum MyLovelyEnum
{
FirstSelection,
TheOtherSelection,
YetAnotherOne
};
I got a property in my DataContext:
public MyLovelyEnum VeryLovelyEnum { get; set; }
And I got three RadioButtons in my WPF client.
<RadioButton Margin="3">First Selection</RadioButton>
<RadioButton Margin="3">The Other Selection</RadioButton>
<RadioButton Margin="3">Yet Another one</RadioButton>
Now how do I bind the RadioButtons to the property for a proper two-way binding?
You can further simplify the accepted answer. Instead of typing out the enums as strings in xaml and doing more work in your converter than needed, you can explicitly pass in the enum value instead of a string representation, and as CrimsonX commented, errors get thrown at compile time rather than runtime:
ConverterParameter={x:Static local:YourEnumType.Enum1}
<StackPanel>
<StackPanel.Resources>
<local:ComparisonConverter x:Key="ComparisonConverter" />
</StackPanel.Resources>
<RadioButton IsChecked="{Binding Path=YourEnumProperty, Converter={StaticResource ComparisonConverter}, ConverterParameter={x:Static local:YourEnumType.Enum1}}" />
<RadioButton IsChecked="{Binding Path=YourEnumProperty, Converter={StaticResource ComparisonConverter}, ConverterParameter={x:Static local:YourEnumType.Enum2}}" />
</StackPanel>
Then simplify the converter:
public class ComparisonConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value?.Equals(parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value?.Equals(true) == true ? parameter : Binding.DoNothing;
}
}
Edit (Dec 16 '10):
Thanks to anon for suggesting returning Binding.DoNothing rather than DependencyProperty.UnsetValue.
Note - Multiple groups of RadioButtons in same container (Feb 17 '11):
In xaml, if radio buttons share the same parent container, then selecting one will de-select all other's within that container (even if they are bound to a different property). So try to keep your RadioButton's that are bound to a common property grouped together in their own container like a stack panel. In cases where your related RadioButtons cannot share a single parent container, then set the GroupName property of each RadioButton to a common value to logically group them.
Edit (Apr 5 '11):
Simplified ConvertBack's if-else to use a Ternary Operator.
Note - Enum type nested in a class (Apr 28 '11):
If your enum type is nested in a class (rather than directly in the namespace), you might be able to use the '+' syntax to access the enum in XAML as stated in a (not marked) answer to the question :
ConverterParameter={x:Static local:YourClass+YourNestedEnumType.Enum1}
Due to this Microsoft Connect Issue, however, the designer in VS2010 will no longer load stating "Type 'local:YourClass+YourNestedEnumType' was not found.", but the project does compile and run successfully. Of course, you can avoid this issue if you are able to move your enum type to the namespace directly.
Edit (Jan 27 '12):
If using Enum flags, the converter would be as follows:
public class EnumToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return ((Enum)value).HasFlag((Enum)parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value.Equals(true) ? parameter : Binding.DoNothing;
}
}
Edit (May 7 '15):
In case of a Nullable Enum (that is **not** asked in the question, but can be needed in some cases, e.g. ORM returning null from DB or whenever it might make sense that in the program logic the value is not provided), remember to add an initial null check in the Convert Method and return the appropriate bool value, that is typically false (if you don't want any radio button selected), like below:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null) {
return false; // or return parameter.Equals(YourEnumType.SomeDefaultValue);
}
return value.Equals(parameter);
}
Note - NullReferenceException (Oct 10 '18):
Updated the example to remove the possibility of throwing a NullReferenceException. `IsChecked` is a nullable type so returning `Nullable` seems a reasonable solution.
You could use a more generic converter
public class EnumBooleanConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string parameterString = parameter as string;
if (parameterString == null)
return DependencyProperty.UnsetValue;
if (Enum.IsDefined(value.GetType(), value) == false)
return DependencyProperty.UnsetValue;
object parameterValue = Enum.Parse(value.GetType(), parameterString);
return parameterValue.Equals(value);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string parameterString = parameter as string;
if (parameterString == null)
return DependencyProperty.UnsetValue;
return Enum.Parse(targetType, parameterString);
}
#endregion
}
And in the XAML-Part you use:
<Grid>
<Grid.Resources>
<l:EnumBooleanConverter x:Key="enumBooleanConverter" />
</Grid.Resources>
<StackPanel >
<RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=FirstSelection}">first selection</RadioButton>
<RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=TheOtherSelection}">the other selection</RadioButton>
<RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=YetAnotherOne}">yet another one</RadioButton>
</StackPanel>
</Grid>
For the EnumToBooleanConverter answer:
Instead of returning DependencyProperty.UnsetValue consider returning Binding.DoNothing for the case where the radio button IsChecked value becomes false.
The former indicates a problem (and might show the user a red rectangle or similar validation indicators) while the latter just indicates that nothing should be done, which is what is wanted in that case.
http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.convertback.aspx
http://msdn.microsoft.com/en-us/library/system.windows.data.binding.donothing.aspx
I would use the RadioButtons in a ListBox, and then bind to the SelectedValue.
This is an older thread about this topic, but the base idea should be the same: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/323d067a-efef-4c9f-8d99-fecf45522395/
For UWP, it is not so simple: You must jump through an extra hoop to pass a field value as a parameter.
Example 1
Valid for both WPF and UWP.
<MyControl>
<MyControl.MyProperty>
<Binding Converter="{StaticResource EnumToBooleanConverter}" Path="AnotherProperty">
<Binding.ConverterParameter>
<MyLibrary:MyEnum>Field</MyLibrary:MyEnum>
</Binding.ConverterParameter>
</MyControl>
</MyControl.MyProperty>
</MyControl>
Example 2
Valid for both WPF and UWP.
...
<MyLibrary:MyEnum x:Key="MyEnumField">Field</MyLibrary:MyEnum>
...
<MyControl MyProperty="{Binding AnotherProperty, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={StaticResource MyEnumField}}"/>
Example 3
Valid only for WPF!
<MyControl MyProperty="{Binding AnotherProperty, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={x:Static MyLibrary:MyEnum.Field}}"/>
UWP doesn't support x:Static so Example 3 is out of the question; assuming you go with Example 1, the result is more verbose code. Example 2 is slightly better, but still not ideal.
Solution
public abstract class EnumToBooleanConverter<TEnum> : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var Parameter = parameter as string;
if (Parameter == null)
return DependencyProperty.UnsetValue;
if (Enum.IsDefined(typeof(TEnum), value) == false)
return DependencyProperty.UnsetValue;
return Enum.Parse(typeof(TEnum), Parameter).Equals(value);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
var Parameter = parameter as string;
return Parameter == null ? DependencyProperty.UnsetValue : Enum.Parse(typeof(TEnum), Parameter);
}
}
Then, for each type you wish to support, define a converter that boxes the enum type.
public class MyEnumToBooleanConverter : EnumToBooleanConverter<MyEnum>
{
//Nothing to do!
}
The reason it must be boxed is because there's seemingly no way to reference the type in the ConvertBack method; the boxing takes care of that. If you go with either of the first two examples, you can just reference the parameter type, eliminating the need to inherit from a boxed class; if you wish to do it all in one line and with least verbosity possible, the latter solution is ideal.
Usage resembles Example 2, but is, in fact, less verbose.
<MyControl MyProperty="{Binding AnotherProperty, Converter={StaticResource MyEnumToBooleanConverter}, ConverterParameter=Field}"/>
The downside is you must define a converter for each type you wish to support.
I've created a new class to handle binding RadioButtons and CheckBoxes to enums. It works for flagged enums (with multiple checkbox selections) and non-flagged enums for single-selection checkboxes or radio buttons. It also requires no ValueConverters at all.
This might look more complicated at first, however, once you copy this class into your project, it's done. It's generic so it can easily be reused for any enum.
public class EnumSelection<T> : INotifyPropertyChanged where T : struct, IComparable, IFormattable, IConvertible
{
private T value; // stored value of the Enum
private bool isFlagged; // Enum uses flags?
private bool canDeselect; // Can be deselected? (Radio buttons cannot deselect, checkboxes can)
private T blankValue; // what is considered the "blank" value if it can be deselected?
public EnumSelection(T value) : this(value, false, default(T)) { }
public EnumSelection(T value, bool canDeselect) : this(value, canDeselect, default(T)) { }
public EnumSelection(T value, T blankValue) : this(value, true, blankValue) { }
public EnumSelection(T value, bool canDeselect, T blankValue)
{
if (!typeof(T).IsEnum) throw new ArgumentException($"{nameof(T)} must be an enum type"); // I really wish there was a way to constrain generic types to enums...
isFlagged = typeof(T).IsDefined(typeof(FlagsAttribute), false);
this.value = value;
this.canDeselect = canDeselect;
this.blankValue = blankValue;
}
public T Value
{
get { return value; }
set
{
if (this.value.Equals(value)) return;
this.value = value;
OnPropertyChanged();
OnPropertyChanged("Item[]"); // Notify that the indexer property has changed
}
}
[IndexerName("Item")]
public bool this[T key]
{
get
{
int iKey = (int)(object)key;
return isFlagged ? ((int)(object)value & iKey) == iKey : value.Equals(key);
}
set
{
if (isFlagged)
{
int iValue = (int)(object)this.value;
int iKey = (int)(object)key;
if (((iValue & iKey) == iKey) == value) return;
if (value)
Value = (T)(object)(iValue | iKey);
else
Value = (T)(object)(iValue & ~iKey);
}
else
{
if (this.value.Equals(key) == value) return;
if (!value && !canDeselect) return;
Value = value ? key : blankValue;
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
And for how to use it, let's say you have an enum for running a task manually or automatically, and can be scheduled for any days of the week, and some optional options...
public enum StartTask
{
Manual,
Automatic
}
[Flags()]
public enum DayOfWeek
{
Sunday = 1 << 0,
Monday = 1 << 1,
Tuesday = 1 << 2,
Wednesday = 1 << 3,
Thursday = 1 << 4,
Friday = 1 << 5,
Saturday = 1 << 6
}
public enum AdditionalOptions
{
None = 0,
OptionA,
OptionB
}
Now, here's how easy it is to use this class:
public class MyViewModel : ViewModelBase
{
public MyViewModel()
{
StartUp = new EnumSelection<StartTask>(StartTask.Manual);
Days = new EnumSelection<DayOfWeek>(default(DayOfWeek));
Options = new EnumSelection<AdditionalOptions>(AdditionalOptions.None, true, AdditionalOptions.None);
}
public EnumSelection<StartTask> StartUp { get; private set; }
public EnumSelection<DayOfWeek> Days { get; private set; }
public EnumSelection<AdditionalOptions> Options { get; private set; }
}
And here's how easy it is to bind checkboxes and radio buttons with this class:
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<!-- Using RadioButtons for exactly 1 selection behavior -->
<RadioButton IsChecked="{Binding StartUp[Manual]}">Manual</RadioButton>
<RadioButton IsChecked="{Binding StartUp[Automatic]}">Automatic</RadioButton>
</StackPanel>
<StackPanel Orientation="Horizontal">
<!-- Using CheckBoxes for 0 or Many selection behavior -->
<CheckBox IsChecked="{Binding Days[Sunday]}">Sunday</CheckBox>
<CheckBox IsChecked="{Binding Days[Monday]}">Monday</CheckBox>
<CheckBox IsChecked="{Binding Days[Tuesday]}">Tuesday</CheckBox>
<CheckBox IsChecked="{Binding Days[Wednesday]}">Wednesday</CheckBox>
<CheckBox IsChecked="{Binding Days[Thursday]}">Thursday</CheckBox>
<CheckBox IsChecked="{Binding Days[Friday]}">Friday</CheckBox>
<CheckBox IsChecked="{Binding Days[Saturday]}">Saturday</CheckBox>
</StackPanel>
<StackPanel Orientation="Horizontal">
<!-- Using CheckBoxes for 0 or 1 selection behavior -->
<CheckBox IsChecked="{Binding Options[OptionA]}">Option A</CheckBox>
<CheckBox IsChecked="{Binding Options[OptionB]}">Option B</CheckBox>
</StackPanel>
</StackPanel>
When the UI loads, the "Manual" radio button will be selected and you can alter your selection between "Manual" or "Automatic" but either one of them must always be selected.
Every day of the week will be unchecked, but any number of them can be checked or unchecked.
"Option A" and "Option B" will both initially be unchecked. You can check one or the other, checking one will uncheck the other (similar to RadioButtons), but now you can also uncheck both of them (which you cannot do with WPF's RadioButton, which is why CheckBox is being used here)
This work for Checkbox too.
public class EnumToBoolConverter:IValueConverter
{
private int val;
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int intParam = (int)parameter;
val = (int)value;
return ((intParam & val) != 0);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
val ^= (int)parameter;
return Enum.Parse(targetType, val.ToString());
}
}
Binding a single enum to multiple checkboxes.
You can create the radio buttons dynamically, ListBox can help you do that, without converters, quite simple.
The concrete steps are below:
create a ListBox and set the ItemsSource for the listbox as the enum MyLovelyEnum and binding the SelectedItem of the ListBox to the VeryLovelyEnum property.
then the Radio Buttons for each ListBoxItem will be created.
Step 1: add the enum to static resources for your Window, UserControl or Grid etc.
<Window.Resources>
<ObjectDataProvider MethodName="GetValues"
ObjectType="{x:Type system:Enum}"
x:Key="MyLovelyEnum">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:MyLovelyEnum" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
Step 2: Use the List Box and Control Template to populate each item inside as Radio button
<ListBox ItemsSource="{Binding Source={StaticResource MyLovelyEnum}}" SelectedItem="{Binding VeryLovelyEnum, Mode=TwoWay}" >
<ListBox.Resources>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<RadioButton
Content="{TemplateBinding ContentPresenter.Content}"
IsChecked="{Binding Path=IsSelected,
RelativeSource={RelativeSource TemplatedParent},
Mode=TwoWay}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
</ListBox>
The advantage is: if someday your enum class changes, you do not need to update the GUI (XAML file).
References:
https://brianlagunas.com/a-better-way-to-data-bind-enums-in-wpf/
One way to handle this would be to have separate bool properties in your ViewModel class. Here is how I've handled with such a situation:
ViewModel:
public enum MyLovelyEnum { FirstSelection, TheOtherSelection, YetAnotherOne };
private MyLovelyEnum CurrentSelection;
public bool FirstSelectionProperty
{
get
{
return CurrentSelection == MyLovelyEnum.FirstSelection;
}
set
{
if (value)
CurrentSelection = MyLovelyEnum.FirstSelection;
}
}
public bool TheOtherSelectionProperty
{
get
{
return CurrentSelection == MyLovelyEnum.TheOtherSelection;
}
set
{
if (value)
CurrentSelection = MyLovelyEnum.TheOtherSelection;
}
}
public bool YetAnotherOneSelectionProperty
{
get
{
return CurrentSelection == MyLovelyEnum.YetAnotherOne;
}
set
{
if (value)
CurrentSelection = MyLovelyEnum.YetAnotherOne;
}
}
XAML:
<RadioButton IsChecked="{Binding SimilaritySort, Mode=TwoWay}">Similarity</RadioButton>
<RadioButton IsChecked="{Binding DateInsertedSort, Mode=TwoWay}">Date Inserted</RadioButton>
<RadioButton IsChecked="{Binding DateOfQuestionSort, Mode=TwoWay}">Date of Question</RadioButton>
<RadioButton IsChecked="{Binding DateModifiedSort, Mode=TwoWay}">Date Modified</RadioButton>
It's not as robust or dynamic as some of the other solutions, but the nice thing is it's very self-contained and doesn't require creating custom converters or anything like that.
Based on the EnumToBooleanConverter from Scott.
I noticed that the ConvertBack method doesn't work on the Enum with flags code.
I've tried the following code:
public class EnumHasFlagToBooleanConverter : IValueConverter
{
private object _obj;
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
_obj = value;
return ((Enum)value).HasFlag((Enum)parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value.Equals(true))
{
if (((Enum)_obj).HasFlag((Enum)parameter))
{
// Do nothing
return Binding.DoNothing;
}
else
{
int i = (int)_obj;
int ii = (int)parameter;
int newInt = i+ii;
return (NavigationProjectDates)newInt;
}
}
else
{
if (((Enum)_obj).HasFlag((Enum)parameter))
{
int i = (int)_obj;
int ii = (int)parameter;
int newInt = i-ii;
return (NavigationProjectDates)newInt;
}
else
{
// do nothing
return Binding.DoNothing;
}
}
}
}
The only thing that I can't get to work is to do a cast from int to targetType so I made it hardcoded to NavigationProjectDates, the enum that I use. And, targetType == NavigationProjectDates...
Edit for more generic Flags Enum converter:
public class FlagsEnumToBooleanConverter : IValueConverter {
private int _flags=0;
public object Convert(object value, Type targetType, object parameter, string language) {
if (value == null) return false;
_flags = (int) value;
Type t = value.GetType();
object o = Enum.ToObject(t, parameter);
return ((Enum)value).HasFlag((Enum)o);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
if (value?.Equals(true) ?? false) {
_flags = _flags | (int) parameter;
}
else {
_flags = _flags & ~(int) parameter;
}
return _flags;
}
}
A TwoWay Binding solution to UWP that takes the usage of Nullable:
C# Part:
public class EnumConverter : IValueConverter
{
public Type EnumType { get; set; }
public object Convert(object value, Type targetType, object parameter, string lang)
{
if (parameter is string enumString)
{
if (!Enum.IsDefined(EnumType, value)) throw new ArgumentException("value must be an Enum!");
var enumValue = Enum.Parse(EnumType, enumString);
return enumValue.Equals(value);
}
return value.Equals(Enum.ToObject(EnumType,parameter));
}
public object ConvertBack(object value, Type targetType, object parameter, string lang)
{
if (parameter is string enumString)
return value?.Equals(true) == true ? Enum.Parse(EnumType, enumString) : null;
return value?.Equals(true) == true ? Enum.ToObject(EnumType, parameter) : null;
}
}
Here the null value acts as the Binding.DoNothing.
private YourEnum? _yourEnum = YourEnum.YourDefaultValue; //put a default value here
public YourEnum? YourProperty
{
get => _yourEnum;
set{
if (value == null) return;
_yourEnum = value;
}
}
Xaml Part:
...
<Page.Resources>
<ResourceDictionary>
<helper:EnumConverter x:Key="YourConverter" EnumType="yournamespace:YourEnum" />
</ResourceDictionary>
</Page.Resources>
...
<RadioButton GroupName="YourGroupName" IsChecked="{Binding Converter={StaticResource YourConverter}, Mode=TwoWay, Path=YourProperty, ConverterParameter=YourEnumString}">
First way (parameter of type string)
</RadioButton>
<RadioButton GroupName="LineWidth">
<RadioButton.IsChecked>
<Binding
Converter="{StaticResource PenWidthConverter}"
Mode="TwoWay" Path="PenWidth">
<Binding.ConverterParameter>
<yournamespace:YourEnum>YourEnumString</yournamespace:YourEnum>
</Binding.ConverterParameter>
</Binding>
</RadioButton.IsChecked>
Second way (parameter of type YourEnum (actually it was converted to int when passed to converter))
</RadioButton>