Switch (Select) statement in Xaml Binding? - wpf

Is there a way to create a conditional binding in XAML?
Example:
<Window x:Name="Me" DataContext="{Binding ElementName=Me}">
<TextBlock>
<TextBlock.Text>
<SelectBinding Binding="{Binding MyValue}">
<Case Value="Value1" Value="value is 1!">
<Case Value="Value2" Value="value is 2!">
<Case Value="Value3" Value="value is 3!">
</SelectBinding >
</TextBlock.Text>
</TextBlock>
</Window>
Bottom line, I want to set a TextBlock value according to another value of Binding, that can be of a list of cases where each case (or cases) is addressed to the appropriate output/setter.
Maybe I can use a DataTrigger in my case, I just don't know exactly how I am gonna do it, since I am not using any DataTemplate here.
Update
In my scenario, I am having a UserControl that has several controls.
I want that according to a certain property in the UserControl.DataContext data-item, other controls in the user control should get affected accordingly. Basically same as my example above just that each case leads to a list of Setters.

use a DataTrigger
(EDITED - original had slight mistake)
<TextBlock>
<TextBlock.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding MyValue}" Value="Value1">
<Setter Property="TextBlock.Text" Value="value is 1!"/>
</DataTrigger>
<DataTrigger Binding="{Binding MyValue}" Value="Value2">
<Setter Property="TextBlock.Text" Value="value is 2!"/>
</DataTrigger>
<DataTrigger Binding="{Binding MyValue}" Value="Value3">
<Setter Property="TextBlock.Text" Value="value is 3!"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>

You have a number of options...
You could use a 'DataTrigger' by applying a 'Style' to your text block (use 'Style.Triggers').
You could create a converter that would convert your 'MyValue' into the appropriate text.
You could create another property on whatever your data source is (ideally this would be a ViewModel-style class) that reflects the text that should be displayed. Update the property from code and bind directly to it, instead of putting the logic in XAML.
Really I'd see this as a stylistic/design choice - none of the above are inherently better or worse, they're just suited to different scenarios.

Try to use the Switch Converter written by Josh:
SwitchConverter –
A "switch statement" for XAML -
http://josheinstein.com/blog/index.php/2010/06/switchconverter-a-switch-statement-for-xaml/
Edit:
Here is code of SwitchConverter as Josh's site seems to be down -
/// <summary>
/// A converter that accepts <see cref="SwitchConverterCase"/>s and converts them to the
/// Then property of the case.
/// </summary>
[ContentProperty("Cases")]
public class SwitchConverter : IValueConverter
{
// Converter instances.
List<SwitchConverterCase> _cases;
#region Public Properties.
/// <summary>
/// Gets or sets an array of <see cref="SwitchConverterCase"/>s that this converter can use to produde values from.
/// </summary>
public List<SwitchConverterCase> Cases { get { return _cases; } set { _cases = value; } }
#endregion
#region Construction.
/// <summary>
/// Initializes a new instance of the <see cref="SwitchConverter"/> class.
/// </summary>
public SwitchConverter()
{
// Create the cases array.
_cases = new List<SwitchConverterCase>();
}
#endregion
/// <summary>
/// Converts a value.
/// </summary>
/// <param name="value">The value produced by the binding source.</param>
/// <param name="targetType">The type of the binding target property.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
/// <returns>
/// A converted value. If the method returns null, the valid null value is used.
/// </returns>
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
// This will be the results of the operation.
object results = null;
// I'm only willing to convert SwitchConverterCases in this converter and no nulls!
if (value == null) throw new ArgumentNullException("value");
// I need to find out if the case that matches this value actually exists in this converters cases collection.
if (_cases != null && _cases.Count > 0)
for (int i = 0; i < _cases.Count; i++)
{
// Get a reference to this case.
SwitchConverterCase targetCase = _cases[i];
// Check to see if the value is the cases When parameter.
if (value == targetCase || value.ToString().ToUpper() == targetCase.When.ToString().ToUpper())
{
// We've got what we want, the results can now be set to the Then property
// of the case we're on.
results = targetCase.Then;
// All done, get out of the loop.
break;
}
}
// return the results.
return results;
}
/// <summary>
/// Converts a value.
/// </summary>
/// <param name="value">The value that is produced by the binding target.</param>
/// <param name="targetType">The type to convert to.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
/// <returns>
/// A converted value. If the method returns null, the valid null value is used.
/// </returns>
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
/// <summary>
/// Represents a case for a switch converter.
/// </summary>
[ContentProperty("Then")]
public class SwitchConverterCase
{
// case instances.
string _when;
object _then;
#region Public Properties.
/// <summary>
/// Gets or sets the condition of the case.
/// </summary>
public string When { get { return _when; } set { _when = value; } }
/// <summary>
/// Gets or sets the results of this case when run through a <see cref="SwitchConverter"/>
/// </summary>
public object Then { get { return _then; } set { _then = value; } }
#endregion
#region Construction.
/// <summary>
/// Switches the converter.
/// </summary>
public SwitchConverterCase()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SwitchConverterCase"/> class.
/// </summary>
/// <param name="when">The condition of the case.</param>
/// <param name="then">The results of this case when run through a <see cref="SwitchConverter"/>.</param>
public SwitchConverterCase(string when, object then)
{
// Hook up the instances.
this._then = then;
this._when = when;
}
#endregion
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
return string.Format("When={0}; Then={1}", When.ToString(), Then.ToString());
}
}

I made an simplified, updated converter based on the accepted answer.
It also allows a string comparison and a default case to be set:
[ContentProperty("Cases")]
public class SwitchConverter : IValueConverter
{
public SwitchConverter()
{
Cases = new List<SwitchConverterCase>();
}
public List<SwitchConverterCase> Cases { get; set; }
public StringComparison StringComparisonType { get; set; } = StringComparison.InvariantCulture;
public object Default { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || Cases == null)
{
return DependencyProperty.UnsetValue;
}
SwitchConverterCase result = Cases.FirstOrDefault(c => string.Equals(value.ToString(), c.When, StringComparisonType));
return result != null ? result.Then : Default;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
The SwitchConverterCase class:
[ContentProperty("Then")]
public class SwitchConverterCase
{
public SwitchConverterCase()
{
}
public SwitchConverterCase(string when, object then)
{
When = when;
Then = then;
}
public string When { get; set; }
public object Then { get; set; }
public override string ToString() => $"When={When}; Then={Then}";
}
Example usage:
<con:SwitchConverter x:Key="StyleConverter"
Default="{x:Static FontWeights.Normal}">
<con:SwitchConverterCase When="pageHeader"
Then="{x:Static FontWeights.Bold}" />
<con:SwitchConverterCase When="header"
Then="{x:Static FontWeights.SemiBold}" />
<con:SwitchConverterCase When="smallText"
Then="{x:Static FontWeights.Light}" />
<con:SwitchConverterCase When="tinyText"
Then="{x:Static FontWeights.Thin}" />
</con:SwitchConverter>
<TextBlock FontWeight="{Binding Style, Converter={StaticResource StyleConverter}}" />
Or inline:
<TextBlock>
<TextBlock.FontWeight>
<Binding Path="Style">
<Binding.Converter>
<con:SwitchConverter Default="{x:Static FontWeights.Normal}">
<con:SwitchConverterCase When="pageHeader"
Then="{x:Static FontWeights.Bold}" />
<!-- etc -->
</con:SwitchConverter>
</Binding.Converter>
</Binding>
</TextBlock.FontWeight>
</TextBlock>

You could just use a converter as Dan suggested...
public class MyValueConverter : IValueConverter
{
public object Convert(
object value,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
{
string myValue = value.ToString();
string output;
switch(myValue)
{
case "Value1":
output = "Value is 1";
break;
case "Value2":
output = "Value is 2";
break;
case "Value3":
output = "Value is 3";
break;
default:
output = "Invalid Value";
break;
}
return output;
}
public object ConvertBack(
object value,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
{
//Put reverse logic here
throw new NotImplementedException();
}
}
You would then use this from within your xaml...
<TextBlock
Text="{Binding MyValue, Converter={StaticResource MyValueConverter}}"/>

Related

WPF two-way binding does not work for checkboxes inside a combobox

I've tried lots of solutions online but I still get this issue.
I have a combobox whose item source is a list of customized class. Each element in the source is displayed as a checkbox in the combobox. Now I have a button whose "Click" function is to uncheck all the checkboxes.
The customized class:
public class LinkObject: INotifyPropertyChanged
{
public int index { set; get; }
public string LO_Name { set; get; }
private bool _checkStatus { set; get; }
public event PropertyChangedEventHandler PropertyChanged;
public void Notify(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public bool checkStatus
{
get { return _checkStatus; }
set
{
_checkStatus = value;
Notify("IsChecked");
}
}
}
The XAML:
<ComboBox Name="cbx1" Grid.ColumnSpan="2" HorizontalAlignment="Left" Margin="126,82,0,0" VerticalAlignment="Top" Width="50" Height="20" IsEditable="True" IsTextSearchEnabled="True" StaysOpenOnEdit="True" TextBoxBase.TextChanged="cbx1_TextChanged">
<ComboBox.ItemTemplate>
<DataTemplate>
<CheckBox Name="cbk1" IsChecked="{Binding checkStatus, Mode=TwoWay}" CommandParameter="{Binding index}" Checked="chk_Checked" Unchecked="chk_Unchecked">
<CheckBox.Content>
<TextBlock Text="{Binding LO_Name}"/>
</CheckBox.Content>
</CheckBox>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
Main function by initialization:
cbx1.ItemsSource = LinkObjectsList_cbx1;
LinkObjectsList_cbx1 is a List<LinkObject>.
The button has a name "clearAllTopView", the click function is:
private void clearAllTopViewBtn_Click(object sender, RoutedEventArgs e)
{
LinkObjectsList_cbx1.Where(l => l.checkStatus == true).ToList().ForEach(lo => lo.checkStatus = false);
}
But when I click the button, nothing happens. Could someone give me a hint or advice? Thank you.
You have an accidental error due to name confusion.
In order not to make such simple but subtle mistakes, I advise you to use a simple base class, but with a better implementation of INPC.
Here is my version of this class.
Copy it and include it in your Solution.
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Simplified
{
/// <summary>Base class with implementation of the <see cref="INotifyPropertyChanged"/> interface.</summary>
public abstract class BaseInpc : INotifyPropertyChanged
{
/// <inheritdoc cref="INotifyPropertyChanged"/>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>The protected method for raising the event <see cref = "PropertyChanged"/>.</summary>
/// <param name="propertyName">The name of the changed property.
/// If the value is not specified, the name of the method in which the call was made is used.</param>
protected void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary> Protected method for assigning a value to a field and raising
/// an event <see cref = "PropertyChanged" />. </summary>
/// <typeparam name = "T"> The type of the field and assigned value. </typeparam>
/// <param name = "propertyField"> Field reference. </param>
/// <param name = "newValue"> The value to assign. </param>
/// <param name = "propertyName"> The name of the changed property.
/// If no value is specified, then the name of the method
/// in which the call was made is used. </param>
/// <remarks> The method is intended for use in the property setter. <br/>
/// To check for changes,
/// used the <see cref = "object.Equals (object, object)" /> method.
/// If the assigned value is not equivalent to the field value,
/// then it is assigned to the field. <br/>
/// After the assignment, an event is created <see cref = "PropertyChanged" />
/// by calling the method <see cref = "RaisePropertyChanged (string)" />
/// passing the parameter <paramref name = "propertyName" />. <br/>
/// After the event is created,
/// the <see cref = "OnPropertyChanged (string, object, object)" />
/// method is called. </remarks>
protected void Set<T>(ref T propertyField, T newValue, [CallerMemberName] string propertyName = null)
{
if (!object.Equals(propertyField, newValue))
{
T oldValue = propertyField;
propertyField = newValue;
RaisePropertyChanged(propertyName);
OnPropertyChanged(propertyName, oldValue, newValue);
}
}
/// <summary> The protected virtual method is called after the property has been assigned a value and after the event is raised <see cref = "PropertyChanged" />. </summary>
/// <param name = "propertyName"> The name of the changed property. </param>
/// <param name = "oldValue"> The old value of the property. </param>
/// <param name = "newValue"> The new value of the property. </param>
/// <remarks> Can be overridden in derived classes to respond to property value changes. <br/>
/// It is recommended to call the base method as the first operator in the overridden method. <br/>
/// If the overridden method does not call the base class, then an unwanted change in the base class logic is possible. </remarks>
protected virtual void OnPropertyChanged(string propertyName, object oldValue, object newValue) { }
}
}
With this basic implementation, your entity class will have code like this:
using Simplified;
namespace Febr20y
{
public class LinkObject : BaseInpc
{
public int Index { set; get; }
public string LO_Name { set; get; }
private bool _checkStatus;
public bool CheckStatus { get => _checkStatus; set => Set(ref _checkStatus, value); }
}
}
This is not relevant to your question, but I advise you to follow the Naming Guidelines.
Namely, property names must begin with the Upper letter.

Implement file explorer based on tree view with multiple selection

I`m beginner WPF. I developing a new project at my work and I need to insert a file explorer control with multiple selection.
The concept need to be similar to acronis file explorer: (Treeview with checkboxes)
Look at the left container, I need to implement something similar to this,
I habe searched alot through google and I saw lot of implementations but nothing wasn`t similar to this.
Because I don`t have alot experience in WPF it quite difficult for me to start.
Do you have some tips or similar projects which might help me do it?
My project based on MVVM DP.
Thanks
Remodelling the Treeview is very easy, you start with your collection that you want to bind to, i.e.
<Grid>
<TreeView ItemsSource="{Binding Folders}"/>
</Grid>
However you then need to define how to display the data you have bound to. I'm assuming that your items are just an IEnumerable (any list or array) of FolderViewModels and FileViewModels (both have a Name property), so now we need to say how to display those. You do that by defining a DataTemplate and since this is for a tree we use a HeirarchicalDataTemplate as that also defines subItems
<Grid.Resources>
<HierarchicalDataTemplate DataType="{x:Type viewModel:FolderViewModel}"
ItemsSource="{Binding SubFoldersAndFiles}">
<CheckBox Content="{Binding Name}"/>
</HierarchicalDataTemplate>
<Grid.Resources/>
Files are the same but dont need sub items
<HierarchicalDataTemplate DataType="{x:Type viewModel:FolderViewModel}">
<CheckBox Content="{Binding Name}"/>
</HierarchicalDataTemplate>
So putting it all together you get
<Grid>
<Grid.Resources>
<HierarchicalDataTemplate DataType="{x:Type viewModel:FolderViewModel}"
ItemsSource="{Binding SubFoldersAndFiles}">
<CheckBox Content="{Binding Name}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type viewModel:FolderViewModel}">
<CheckBox Content="{Binding Name}"/>
</HierarchicalDataTemplate>
<Grid.Resources/>
<TreeView ItemsSource="{Binding Folders}"/>
</Grid>
Icons
If you want to show icons then you change the content in the CheckBox, I'm assuming you will define an Image on your ViewModel.
<CheckBox>
<CheckBox.Content>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Image}"/>
<TextBlock Text="{Binding Name}"/>
</StackPanel>
</CheckBox.Content>
Selection
Finally you have to handle the selection of items. I'd advise adding an IsSelected property to your FileViewModel and FolderViewModels. For files this is incredibly simple, its just a bool.
public class FileViewModel : INotifyProperty
...
public bool IsSelected //Something here to handle get/set and NotifyPropertyChanged that depends on your MVVM framework, I use ReactiveUI a lot so that's this syntax
{
get { return _IsSelected;}
set { this.RaiseAndSetIfChanged(x=>x.IsSelected, value); }
}
and
<CheckBox IsChecked="{Binding IsSelected}">
Its slightly more complicated with FolderViewModel and I'll look at the logic in a second. First the Xaml, just replace the current CheckBox declaration with
<CheckBox IsThreeState="True" IsChecked="{Binding IsSelected}">
<!--IsChecked = True, False or null-->
So now we need to return a set of Nullable<bool> (aka bool?).
public bool? IsSelected
{
get
{
if (SubFoldersAndFiles.All(x=>x.IsSelected) return true;
if (SubFoldersAndFiles.All(x=>x.IsSelected==false) return false;
return null;
}
set
{
// We can't set to indeterminate at folder level so we have to set to
// set to oposite of what we have now
if(value == null)
value = !IsSelected;
foreach(var x in SubFoldersAndFiles)
x.IsSelected = value;
}
Or something very similar...
After taking a look at the answer by #AlSki, I decided it is neither intuitive nor versatile enough for my liking and came up with my own solution. The disadvantage of using my solution, however, is it requires a tad bit more boilerplate. On the other hand, it offers a LOT more flexibility.
The samples below assume you use .NET 4.6.1 and C# 6.0.
/// <summary>
/// A base for abstract objects (implements INotifyPropertyChanged).
/// </summary>
[Serializable]
public abstract class AbstractObject : INotifyPropertyChanged
{
/// <summary>
///
/// </summary>
[field: NonSerialized()]
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
///
/// </summary>
/// <param name="propertyName"></param>
public void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>
///
/// </summary>
/// <typeparam name="TKind"></typeparam>
/// <param name="Source"></param>
/// <param name="NewValue"></param>
/// <param name="Names"></param>
protected virtual bool SetValue<TKind>(ref TKind Source, TKind NewValue, params string[] Notify)
{
//Set value if the new value is different from the old
if (!Source.Equals(NewValue))
{
Source = NewValue;
//Notify all applicable properties
Notify?.ForEach(i => OnPropertyChanged(i));
return true;
}
return false;
}
/// <summary>
///
/// </summary>
public AbstractObject()
{
}
}
An object with a check state.
/// <summary>
/// Specifies an object with a checked state.
/// </summary>
public interface ICheckable
{
/// <summary>
///
/// </summary>
bool? IsChecked
{
get; set;
}
}
/// <summary>
///
/// </summary>
public class CheckableObject : AbstractObject, ICheckable
{
/// <summary>
///
/// </summary>
[field: NonSerialized()]
public event EventHandler<EventArgs> Checked;
/// <summary>
///
/// </summary>
[field: NonSerialized()]
public event EventHandler<EventArgs> Unchecked;
/// <summary>
///
/// </summary>
[XmlIgnore]
protected bool? isChecked;
/// <summary>
///
/// </summary>
public virtual bool? IsChecked
{
get
{
return isChecked;
}
set
{
if (SetValue(ref isChecked, value, "IsChecked") && value != null)
{
if (value.Value)
{
OnChecked();
}
else OnUnchecked();
}
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override string ToString()
{
return base.ToString();
//return isChecked.ToString();
}
/// <summary>
///
/// </summary>
protected virtual void OnChecked()
{
Checked?.Invoke(this, new EventArgs());
}
/// <summary>
///
/// </summary>
protected virtual void OnUnchecked()
{
Unchecked?.Invoke(this, new EventArgs());
}
/// <summary>
///
/// </summary>
public CheckableObject() : base()
{
}
/// <summary>
///
/// </summary>
/// <param name="isChecked"></param>
public CheckableObject(bool isChecked = false)
{
IsChecked = isChecked;
}
}
The view model for checked system objects:
/// <summary>
///
/// </summary>
public class CheckableSystemObject : CheckableObject
{
#region Properties
/// <summary>
///
/// </summary>
public event EventHandler Collapsed;
/// <summary>
///
/// </summary>
public event EventHandler Expanded;
bool StateChangeHandled = false;
CheckableSystemObject Parent { get; set; } = default(CheckableSystemObject);
ISystemProvider SystemProvider { get; set; } = default(ISystemProvider);
ConcurrentCollection<CheckableSystemObject> children = new ConcurrentCollection<CheckableSystemObject>();
/// <summary>
///
/// </summary>
public ConcurrentCollection<CheckableSystemObject> Children
{
get
{
return children;
}
private set
{
SetValue(ref children, value, "Children");
}
}
bool isExpanded = false;
/// <summary>
///
/// </summary>
public bool IsExpanded
{
get
{
return isExpanded;
}
set
{
if (SetValue(ref isExpanded, value, "IsExpanded"))
{
if (value)
{
OnExpanded();
}
else OnCollapsed();
}
}
}
bool isSelected = false;
/// <summary>
///
/// </summary>
public bool IsSelected
{
get
{
return isSelected;
}
set
{
SetValue(ref isSelected, value, "IsSelected");
}
}
string path = string.Empty;
/// <summary>
///
/// </summary>
public string Path
{
get
{
return path;
}
set
{
SetValue(ref path, value, "Path");
}
}
bool queryOnExpanded = false;
/// <summary>
///
/// </summary>
public bool QueryOnExpanded
{
get
{
return queryOnExpanded;
}
set
{
SetValue(ref queryOnExpanded, value);
}
}
/// <summary>
///
/// </summary>
public override bool? IsChecked
{
get
{
return isChecked;
}
set
{
if (SetValue(ref isChecked, value, "IsChecked") && value != null)
{
if (value.Value)
{
OnChecked();
}
else OnUnchecked();
}
}
}
#endregion
#region CheckableSystemObject
/// <summary>
///
/// </summary>
/// <param name="path"></param>
/// <param name="systemProvider"></param>
/// <param name="isChecked"></param>
public CheckableSystemObject(string path, ISystemProvider systemProvider, bool? isChecked = false) : base()
{
Path = path;
SystemProvider = systemProvider;
IsChecked = isChecked;
}
#endregion
#region Methods
void Determine()
{
//If it has a parent, determine it's state by enumerating all children, but current instance, which is already accounted for.
if (Parent != null)
{
StateChangeHandled = true;
var p = Parent;
while (p != null)
{
p.IsChecked = Determine(p);
p = p.Parent;
}
StateChangeHandled = false;
}
}
bool? Determine(CheckableSystemObject Root)
{
//Whether or not all children and all children's children have the same value
var Uniform = true;
//If uniform, the value
var Result = default(bool?);
var j = false;
foreach (var i in Root.Children)
{
//Get first child's state
if (j == false)
{
Result = i.IsChecked;
j = true;
}
//If the previous child's state is not equal to the current child's state, it is not uniform and we are done!
else if (Result != i.IsChecked)
{
Uniform = false;
break;
}
}
return !Uniform ? null : Result;
}
void Query(ISystemProvider SystemProvider)
{
children.Clear();
if (SystemProvider != null)
{
foreach (var i in SystemProvider.Query(path))
{
children.Add(new CheckableSystemObject(i, SystemProvider, isChecked)
{
Parent = this
});
}
}
}
/// <summary>
///
/// </summary>
protected override void OnChecked()
{
base.OnChecked();
if (!StateChangeHandled)
{
//By checking the root only, all children are checked automatically
foreach (var i in children)
i.IsChecked = true;
Determine();
}
}
/// <summary>
///
/// </summary>
protected override void OnUnchecked()
{
base.OnUnchecked();
if (!StateChangeHandled)
{
//By unchecking the root only, all children are unchecked automatically
foreach (var i in children)
i.IsChecked = false;
Determine();
}
}
/// <summary>
///
/// </summary>
protected virtual void OnCollapsed()
{
Collapsed?.Invoke(this, new EventArgs());
}
/// <summary>
///
/// </summary>
protected virtual void OnExpanded()
{
Expanded?.Invoke(this, new EventArgs());
if (!children.Any<CheckableSystemObject>() || queryOnExpanded)
BeginQuery(SystemProvider);
}
/// <summary>
///
/// </summary>
/// <param name="SystemProvider"></param>
public async void BeginQuery(ISystemProvider SystemProvider)
{
await Task.Run(() => Query(SystemProvider));
}
#endregion
}
Utilities for querying system objects; note, by defining your own SystemProvider, you can query different types of systems (i.e., local or remote). By default, your local system is queried. If you want to display objects from a remote server like FTP, you'd want to define a SystemProvider that utilizes the appropriate web protocol.
/// <summary>
/// Specifies an object capable of querying system objects.
/// </summary>
public interface ISystemProvider
{
/// <summary>
///
/// </summary>
/// <param name="Path">The path to query.</param>
/// <param name="Source">A source used to make queries.</param>
/// <returns>A list of system object paths.</returns>
IEnumerable<string> Query(string Path, object Source = null);
}
/// <summary>
/// Defines base functionality for an <see cref="ISystemProvider"/>.
/// </summary>
public abstract class SystemProvider : ISystemProvider
{
/// <summary>
///
/// </summary>
/// <param name="Path"></param>
/// <param name="Source"></param>
/// <returns></returns>
public abstract IEnumerable<string> Query(string Path, object Source = null);
}
/// <summary>
/// Defines functionality to query a local system.
/// </summary>
public class LocalSystemProvider : SystemProvider
{
/// <summary>
///
/// </summary>
/// <param name="Path"></param>
/// <param name="Source"></param>
/// <returns></returns>
public override IEnumerable<string> Query(string Path, object Source = null)
{
if (Path.IsNullOrEmpty())
{
foreach (var i in System.IO.DriveInfo.GetDrives())
yield return i.Name;
}
else
{
if (System.IO.Directory.Exists(Path))
{
foreach (var i in System.IO.Directory.EnumerateFileSystemEntries(Path))
yield return i;
}
}
}
}
And then an inherited TreeView, which puts this all together:
/// <summary>
///
/// </summary>
public class SystemObjectPicker : TreeViewExt
{
#region Properties
/// <summary>
///
/// </summary>
public static DependencyProperty QueryOnExpandedProperty = DependencyProperty.Register("QueryOnExpanded", typeof(bool), typeof(SystemObjectPicker), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnQueryOnExpandedChanged));
/// <summary>
///
/// </summary>
public bool QueryOnExpanded
{
get
{
return (bool)GetValue(QueryOnExpandedProperty);
}
set
{
SetValue(QueryOnExpandedProperty, value);
}
}
static void OnQueryOnExpandedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
d.As<SystemObjectPicker>().OnQueryOnExpandedChanged((bool)e.NewValue);
}
/// <summary>
///
/// </summary>
public static DependencyProperty RootProperty = DependencyProperty.Register("Root", typeof(string), typeof(SystemObjectPicker), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnRootChanged));
/// <summary>
///
/// </summary>
public string Root
{
get
{
return (string)GetValue(RootProperty);
}
set
{
SetValue(RootProperty, value);
}
}
static void OnRootChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
d.As<SystemObjectPicker>().OnRootChanged((string)e.NewValue);
}
/// <summary>
///
/// </summary>
static DependencyProperty SystemObjectsProperty = DependencyProperty.Register("SystemObjects", typeof(ConcurrentCollection<CheckableSystemObject>), typeof(SystemObjectPicker), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
/// <summary>
///
/// </summary>
ConcurrentCollection<CheckableSystemObject> SystemObjects
{
get
{
return (ConcurrentCollection<CheckableSystemObject>)GetValue(SystemObjectsProperty);
}
set
{
SetValue(SystemObjectsProperty, value);
}
}
/// <summary>
///
/// </summary>
public static DependencyProperty SystemProviderProperty = DependencyProperty.Register("SystemProvider", typeof(ISystemProvider), typeof(SystemObjectPicker), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSystemProviderChanged));
/// <summary>
///
/// </summary>
public ISystemProvider SystemProvider
{
get
{
return (ISystemProvider)GetValue(SystemProviderProperty);
}
set
{
SetValue(SystemProviderProperty, value);
}
}
static void OnSystemProviderChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
d.As<SystemObjectPicker>().OnSystemProviderChanged((ISystemProvider)e.NewValue);
}
#endregion
#region SystemObjectPicker
/// <summary>
///
/// </summary>
public SystemObjectPicker() : base()
{
SetCurrentValue(SystemObjectsProperty, new ConcurrentCollection<CheckableSystemObject>());
SetCurrentValue(SystemProviderProperty, new LocalSystemProvider());
SetBinding(ItemsSourceProperty, new Binding()
{
Mode = BindingMode.OneWay,
Path = new PropertyPath("SystemObjects"),
Source = this
});
}
#endregion
#region Methods
void OnQueryOnExpandedChanged(CheckableSystemObject Item, bool Value)
{
foreach (var i in Item.Children)
{
i.QueryOnExpanded = Value;
OnQueryOnExpandedChanged(i, Value);
}
}
/// <summary>
///
/// </summary>
/// <param name="Value"></param>
protected virtual void OnQueryOnExpandedChanged(bool Value)
{
foreach (var i in SystemObjects)
OnQueryOnExpandedChanged(i, Value);
}
/// <summary>
///
/// </summary>
/// <param name="Provider"></param>
/// <param name="Root"></param>
protected virtual void OnRefreshed(ISystemProvider Provider, string Root)
{
SystemObjects.Clear();
if (Provider != null)
{
foreach (var i in Provider.Query(Root))
{
SystemObjects.Add(new CheckableSystemObject(i, SystemProvider)
{
QueryOnExpanded = QueryOnExpanded
});
}
}
}
/// <summary>
///
/// </summary>
/// <param name="Value"></param>
protected virtual void OnRootChanged(string Value)
{
OnRefreshed(SystemProvider, Value);
}
/// <summary>
///
/// </summary>
/// <param name="Value"></param>
protected virtual void OnSystemProviderChanged(ISystemProvider Value)
{
OnRefreshed(Value, Root);
}
#endregion
}
Obviously, it's dramatically more complex than #AlSki's answer, but, again, you get more flexibility and the hard stuff is taken care of for you already.
In addition, I have published this code in the latest version of my open source project (3.1) if such a thing interests you; if not, the samples above is all you need to get it working.
If you do not download the project, note the following:
You will find some extension methods that do not exist, which can be supplemented with their counterparts (e.g., IsNullOrEmpty extension is identical to string.IsNullOrEmpty()).
TreeViewExt is a custom TreeView I designed so if you don't care about that, simply change TreeViewExt to TreeView; either way, you should not have to define a special control template for it as it was designed to work with TreeView's existing facilities.
In the sample, I use my own version of a concurrent ObservableCollection; this is so you can query data on a background thread without jumping through hoops. Change this to ObservableCollection and make all queries synchronous OR use your own concurrent ObservableCollection to preserve the asynchronous functionality.
Finally, here is how you would use the control:
<Controls.Extended:SystemObjectPicker>
<Controls.Extended:SystemObjectPicker.ItemContainerStyle>
<Style TargetType="TreeViewItem" BasedOn="{StaticResource {x:Type TreeViewItem}}">
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Style>
</Controls.Extended:SystemObjectPicker.ItemContainerStyle>
<Controls.Extended:SystemObjectPicker.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children, Mode=OneWay}">
<StackPanel Orientation="Horizontal">
<CheckBox
IsChecked="{Binding IsChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Margin="0,0,5,0"/>
<TextBlock
Text="{Binding Path, Converter={StaticResource FileNameConverter}, Mode=OneWay}"/>
</StackPanel>
</HierarchicalDataTemplate>
</Controls.Extended:SystemObjectPicker.ItemTemplate>
</Controls.Extended:SystemObjectPicker>
To Do
Add a property to CheckableSystemObject that exposes a view model for the system object; that way, you can access the FileInfo/DirectoryInfo associated with it's path or some other source of data that otherwise describes it. If the object is remote, you may have already defined your own class to describe it, which could be useful if you have the reference to it.
Catch possible exceptions when querying a local system; if a system object cannot be accessed, it will fail. LocalSystemProvider also fails to address system paths that exceed 260 characters; however, that is beyond the scope of this project.
Note To Moderators
I referenced my own open source project for convenience as I published the above samples in the latest version; my intention is not to self-promote so if referencing your own project is frowned upon, I will proceed to remove the link.

Bound Silverlight Combobox not showing default value with EnumBinder

My models use enums for fixed multiple selections. I'm using Dean Chalk's EnumBinder, found at http://deanchalk.me.uk/post/Enumeration-Binding-In-Silverlight.aspx , to bind to a combo box. Everything seems to work great except the default value isn't shown. The selected index is -1, and it doesn't matter if I bind to SelectedItem or SelectedValue. The combobox works fine otherwise. I have no problems with default values with any other bound comboboxes.
enumbindingsupport.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
/* All of this was once just part of the RichClient sub-namespace
* but it has its uses elsewhere, so it has been moved.
*/
/// <summary>
/// Container for enumeration values.
/// </summary>
/// <remarks>
/// http://deanchalk.me.uk/post/Enumeration-Binding-In-Silverlight.aspx
/// </remarks>
public sealed class EnumContainer
{
public int EnumValue { get; set; }
public string EnumDescription { get; set; }
public object EnumOriginalValue { get; set; }
public override string ToString() {
return EnumDescription;
}
public override bool Equals(object obj) {
if (obj == null)
return false;
if (obj is EnumContainer)
return EnumValue.Equals((int)((EnumContainer)obj).EnumValue);
return EnumValue.Equals((int)obj);
}
public override int GetHashCode() {
return EnumValue.GetHashCode();
}
}
/// <summary>
/// A collection to store a list of EnumContainers that hold enum values.
/// </summary>
/// <remarks>
/// http://deanchalk.me.uk/post/Enumeration-Binding-In-Silverlight.aspx
/// </remarks>
/// <typeparam name="T"></typeparam>
public class EnumCollection<T> : List<EnumContainer> where T : struct
{
public EnumCollection() {
var type = typeof(T);
if (!type.IsEnum)
throw new ArgumentException("This class only supports Enum types");
var fields = typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public);
foreach (var field in fields) {
var container = new EnumContainer();
container.EnumOriginalValue = field.GetValue(null);
container.EnumValue = (int)field.GetValue(null);
container.EnumDescription = field.Name;
var atts = field.GetCustomAttributes(false);
foreach (var att in atts)
if (att is DescriptionAttribute) {
container.EnumDescription = ((DescriptionAttribute)att).Description;
break;
}
Add(container);
}
}
}
enumvalueconverter.cs
using System;
using System.Globalization;
using System.Windows.Data;
/// <summary>
/// Supports two-way binding of enumerations.
/// </summary>
public class EnumValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
CultureInfo culture) {
return (int)value;
}
public object ConvertBack(object value, Type targetType, object parameter,
CultureInfo culture) {
if (value == null)
return null;
if (value.GetType() == targetType)
return value;
return ((EnumContainer)value).EnumOriginalValue;
}
}
enum used:
/// <summary>
/// Describes the available sorting options.
/// </summary>
public enum PeopleSortOptionsEnum
{
[Display(Order = 10)]
[Description("First Name, Last Name")]
FirstNameThenLastName,
[Display(Order = 20)]
[Description("Last Name, First Name")]
LastNameThenFirstName,
[Display(Order = 30)]
Grade,
[Display(Order = 40)]
Gender,
[Display(Order = 50)]
Age
}
property on my model:
/// <summary>
/// This is the list for the enumeration to bind to.
/// </summary>
public EnumCollection<PeopleSortOptionsEnum> AvailableSortOptions
{
get { return new EnumCollection<PeopleSortOptionsEnum>(); }
}
XAML snippet:
<ComboBox ItemsSource="{Binding Path=AvailableSortOptions, Mode=OneWay}" SelectedValue="{Binding Path=Preferences.SortOrder, Mode=TwoWay, Converter={StaticResource EnumConverter}}" Grid.Column="1" Grid.Row="2" Height="32" Margin="48,31,0,0" x:Name="cboSort" VerticalAlignment="Top" />
Where Preferences.SortOrder is of type PeopleSortOptionsEnum, the converter is in my app.xaml as a converter for all enum types.
Anyone have any idea why it won't set the index to the currently selected value? I'm about to just throw some code in the codebehind to set the selectedindex to the currently selected value on load, but I feel so dirty just thinking about it.
Besides this issue, it works wonderfully, so thanks Dean!
Edit Adding the Preferences.SortOrder code:
public PeopleSortOptionsEnum SortOrder
{
get { return sortOrder; }
set
{
if (sortOrder != value)
{
sortOrder = value;
PropertyHasChanged("SortOrder");
}
}
}
The issue is the Convert method on your enum converter class:
public object Convert(object value, Type targetType, object parameter,
CultureInfo culture) {
return (int)value;
}
When the combobox SelectedItem is gets the value from SortOrder it is return in Enum value which this converter is converting to an int. However, the combobox items is a collection of EnumContainer objects, not ints. So it fails to set the selected item.
To resolve the issue you have to do two things. First change your combobox bindings and set the SelectedValuePath:
<ComboBox ItemsSource="{Binding Path=AvailableSortOptions}"
SelectedValue="{Binding Path=SortOrder, Mode=TwoWay, Converter={StaticResource EnumConverter}}"
SelectedValuePath="EnumOriginalValue"/>
Second you have to slightly modify the Convert method on your converter:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
Once I made those two changes it started working as expected.

WPF ContextMenu.ItemsSource not resolving from binding

I have the following XAML on a ToolBar:
<emsprim:SplitButton Mode="Split">
<emsprim:SplitButton.Content>
<Image Source="images/16x16/Full Extent 1.png" />
</emsprim:SplitButton.Content>
<emsprim:SplitButton.ContextMenu>
<ContextMenu ItemsSource="{Binding CommandGroups[ZoomToDefinedExtentsCmds]}">
<ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Command" Value="{Binding Command}" />
<Setter Property="CommandParameter" Value="{Binding ViewID}" />
<Setter Property="Header" Value="{Binding Name}" />
<Setter Property="Icon" Value="{Binding Icon}" />
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
</emsprim:SplitButton.ContextMenu>
</emsprim:SplitButton>
where CommandGroups[ZoomToDefinedExtentsCmds] is an IEnumerable of CommandViewModels. Problem is, when I click on the button, I do not see the list of menu items. However, if I bind the same Datacontext to a Menu, like this:
<MenuItem ItemsSource="{Binding CommandGroups[ZoomToDefinedExtentsCmds]}"
Header="Zoom To"
Margin="5,1,5,0" >
<MenuItem.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Command" Value="{Binding Command}" />
<Setter Property="CommandParameter" Value="{Binding CommandParameter}" />
<Setter Property="Header" Value="{Binding Name}" />
<Setter Property="Icon" Value="{Binding Icon}" />
</Style>
</MenuItem.ItemContainerStyle>
</MenuItem>
I do get the list of MenuItems. Any ideas on what is going on here as there is no binding error in the output VS window. BTW, code for SplitButton is listed below:
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Markup;
using System.Diagnostics;
namespace Controls.Dictionary.Primitives
{
/// <summary>
/// Implemetation of a Split Button
/// </summary>
[TemplatePart(Name = "PART_DropDown", Type = typeof(Button))]
[ContentProperty("Items")]
[DefaultProperty("Items")]
public class SplitButton : Button
{
// AddOwner Dependency properties
public static readonly DependencyProperty PlacementProperty;
public static readonly DependencyProperty PlacementRectangleProperty;
public static readonly DependencyProperty HorizontalOffsetProperty;
public static readonly DependencyProperty VerticalOffsetProperty;
/// <summary>
/// Static Constructor
/// </summary>
static SplitButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(SplitButton), new FrameworkPropertyMetadata(typeof(SplitButton)));
// AddOwner properties from the ContextMenuService class, we need callbacks from these properties
// to update the Buttons ContextMenu properties
PlacementProperty = ContextMenuService.PlacementProperty.AddOwner(typeof(SplitButton), new FrameworkPropertyMetadata(PlacementMode.MousePoint, OnPlacementChanged));
PlacementRectangleProperty = ContextMenuService.PlacementRectangleProperty.AddOwner(typeof(SplitButton), new FrameworkPropertyMetadata(Rect.Empty, OnPlacementRectangleChanged));
HorizontalOffsetProperty = ContextMenuService.HorizontalOffsetProperty.AddOwner(typeof(SplitButton), new FrameworkPropertyMetadata(0.0, OnHorizontalOffsetChanged));
VerticalOffsetProperty = ContextMenuService.VerticalOffsetProperty.AddOwner(typeof(SplitButton), new FrameworkPropertyMetadata(0.0, OnVerticalOffsetChanged));
}
/*
* Properties
*
*/
/// <summary>
/// The Split Button's Items property maps to the base classes ContextMenu.Items property
/// </summary>
public ItemCollection Items
{
get
{
EnsureContextMenuIsValid();
return this.ContextMenu.Items;
}
}
/*
* Dependancy Properties & Callbacks
*
*/
/// <summary>
/// Placement of the Context menu
/// </summary>
public PlacementMode Placement
{
get { return (PlacementMode)GetValue(PlacementProperty); }
set { SetValue(PlacementProperty, value); }
}
/// <summary>
/// Placement Property changed callback, pass the value through to the buttons context menu
/// </summary>
private static void OnPlacementChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
SplitButton s = d as SplitButton;
if (s == null) return;
s.EnsureContextMenuIsValid();
s.ContextMenu.Placement = (PlacementMode)e.NewValue;
}
/// <summary>
/// PlacementRectangle of the Context menu
/// </summary>
public Rect PlacementRectangle
{
get { return (Rect)GetValue(PlacementRectangleProperty); }
set { SetValue(PlacementRectangleProperty, value); }
}
/// <summary>
/// PlacementRectangle Property changed callback, pass the value through to the buttons context menu
/// </summary>
private static void OnPlacementRectangleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
SplitButton s = d as SplitButton;
if (s == null) return;
s.EnsureContextMenuIsValid();
s.ContextMenu.PlacementRectangle = (Rect)e.NewValue;
}
/// <summary>
/// HorizontalOffset of the Context menu
/// </summary>
public double HorizontalOffset
{
get { return (double)GetValue(HorizontalOffsetProperty); }
set { SetValue(HorizontalOffsetProperty, value); }
}
/// <summary>
/// HorizontalOffset Property changed callback, pass the value through to the buttons context menu
/// </summary>
private static void OnHorizontalOffsetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
SplitButton s = d as SplitButton;
if (s == null) return;
s.EnsureContextMenuIsValid();
s.ContextMenu.HorizontalOffset = (double)e.NewValue;
}
/// <summary>
/// VerticalOffset of the Context menu
/// </summary>
public double VerticalOffset
{
get { return (double)GetValue(VerticalOffsetProperty); }
set { SetValue(VerticalOffsetProperty, value); }
}
/// <summary>
/// VerticalOffset Property changed callback, pass the value through to the buttons context menu
/// </summary>
private static void OnVerticalOffsetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
SplitButton s = d as SplitButton;
if (s == null) return;
s.EnsureContextMenuIsValid();
s.ContextMenu.VerticalOffset = (double)e.NewValue;
}
/// <summary>
/// Defines the Mode of operation of the Button
/// </summary>
/// <remarks>
/// The SplitButton two Modes are
/// Split (default), - the button has two parts, a normal button and a dropdown which exposes the ContextMenu
/// Dropdown - the button acts like a combobox, clicking anywhere on the button opens the Context Menu
/// </remarks>
public SplitButtonMode Mode
{
get { return (SplitButtonMode)GetValue(ModeProperty); }
set { SetValue(ModeProperty, value); }
}
public static readonly DependencyProperty ModeProperty = DependencyProperty.Register("Mode", typeof(SplitButtonMode), typeof(SplitButton), new FrameworkPropertyMetadata(SplitButtonMode.Split));
/*
* Methods
*
*/
/// <summary>
/// OnApplyTemplate override, set up the click event for the dropdown if present in the template
/// </summary>
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
// set up the event handlers
ButtonBase dropDown = this.Template.FindName("PART_DropDown", this) as ButtonBase;
if (dropDown != null)
dropDown.Click += DoDropdownClick;
}
/// <summary>
/// Make sure the Context menu is not null
/// </summary>
private void EnsureContextMenuIsValid()
{
if (ContextMenu == null)
ContextMenu = new ContextMenu();
}
/*
* Events
*
*/
/// <summary>
/// Event Handler for the Drop Down Button's Click event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void DoDropdownClick(object sender, RoutedEventArgs e)
{
if (Mode == SplitButtonMode.Dropdown)
return;
if (ContextMenu == null || ContextMenu.HasItems == false) return;
ContextMenu.PlacementTarget = this;
ContextMenu.IsOpen = true;
e.Handled = true;
}
}
}
Problem solved by explicitly setting ContextMenu's DataContext.
ContextMenu is not part of visual tree, therefore, does not resolve DataContext of its "parent'- is one gotcha that gets me every time.
The MenuItem object in your second code snippet, is that outside the SplitButton scope? As in, a direct child of the object container that has the CommandGroups property defined?
I ask because the ContextMenu in the first snippet will have a null DataContext, and as such will not be able to see the CommandGroups property.
I had a similar problem about a year ago, unfortunately, the only way I could solve this was to define the ContextMenu in code and inside the Execute method for a Command. Which enabled me to assign the ItemsSource in code.
To debug DataContext (and other Binding related problems like this) you should create yourself a DebugConverter like:
public class DebugConverter : IValueConverter
{
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)
{
throw new NotImplementedException();
}
}
This will help you debug a troublesome binding issue by creating the Binding like: {Binding Converter={StaticResource debugConverter}} and by setting a break point on the return value; line.

WPF Validating unbound textbox

is it possible to use validation without the Binding part? The thing is my textbox is not bound to any object, but I still want to validate it's content. The only way I've found so far is this:
<TextBox Grid.Row="0" Grid.Column="1" MaxLength="50" x:Name="textBoxTubeName" Margin="5,5,0,5">
<TextBox.Text>
<Binding Path="Name" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay" NotifyOnValidationError="True">
<Binding.ValidationRules>
<validation:InvalidCharactersRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
But again, it only works when the TextBox.Text is bound to something (in this case, the Name property), how would I go about this without binding?
Thanks!
According to the MSDN forums it's not possible yet but it is planned (Note: this is an old post). However, I still can't find a way to do it so it may not be implemented yet.
It is a lot tricky to do from code-behind. Basically, you can set a temporary binding from code and raise the validation error and when the input has valid value you can remove all the temporary binding stuff again.
Here what I use, which I consider a bad practise (but it's better from nothing):
/// <summary>
/// Marks a textBox control as invalid (via validation error) from code.
/// </summary>
/// <param name="textBox">The text box.</param>
/// <param name="errorContent">Content of the error.</param>
public static void ValidationMarkInvalid(TextBox textBox, String errorContent)
{
DependencyProperty textProp = TextBox.TextProperty;
if (!BindingOperations.IsDataBound(textBox, textProp))
{
if (textBox.DataContext == null)
{
textBox.DataContext = new EmptyDataContext();
}
Binding b = new Binding("CodeBehind");
b.FallbackValue = textBox.Text;
b.ValidatesOnExceptions = true;
BindingOperations.SetBinding(textBox, textProp, b);
}
BindingExpression bindingInError =
textBox.GetBindingExpression(TextBox.TextProperty);
var validationError = new ValidationError(
new EmptyValidationRule(),
bindingInError,
errorContent,
new Exception(errorContent));
Validation.MarkInvalid(bindingInError, validationError);
}
/// <summary>
/// Clears the validation error from a textBox.
/// </summary>
/// <param name="textBox">The text box.</param>
public static void ValidationClear(TextBox textBox)
{
DependencyProperty textProp = TextBox.TextProperty;
if (BindingOperations.IsDataBound(textBox, textProp))
{
String value = textBox.Text;
Validation.ClearInvalid(textBox.GetBindingExpression(TextBox.TextProperty));
BindingOperations.ClearBinding(textBox, textProp);
textBox.Text = value;
EmptyDataContext ctx = textBox.DataContext as EmptyDataContext;
if (ctx != null)
{
textBox.DataContext = null;
}
}
}
#region Nested Type: EmptyDataContext
private sealed class EmptyDataContext : INotifyPropertyChanged
{
public Object CodeBehind
{
get
{
throw new FormatException();
}
set
{
throw new FormatException();
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
#endregion
#region Nested Type: EmptyValidationRule
private sealed class EmptyValidationRule : ValidationRule
{
/// <summary>
/// When overridden in a derived class, performs validation checks on a value.
/// </summary>
/// <param name="value">The value from the binding target to check.</param>
/// <param name="cultureInfo">The culture to use in this rule.</param>
/// <returns>
/// A <see cref="T:System.Windows.Controls.ValidationResult"/> object.
/// </returns>
public override ValidationResult Validate(Object value, CultureInfo cultureInfo)
{
return new ValidationResult(false, String.Empty);
}
}
#endregion
Now, from your code-behind you do this:
ValidationMarkInvalid(textBox, "Please enter something valid!");
and to clear the validation:
ValidationClear(textBox);
P.S.: If you don't want to validate on exceptions you can remove the EmptyDataContext class from the above methods.

Resources