Binding formatted text to templated TextBlock - wpf

I have an external control which displays a layout formed from a label and an input control. My label requires special formatting (subscript) but it currently only supports direct text.
So my approach is to create a custom TextBlock implementation, which exposes a new InlineContent dependency property that, once set, converts the content and adds it to it's actual Inlines collection.
For the layout control I add a custom DataTemplate which binds the label content to the InlineContent property of my custom text block.
ExtendedTextBlock.cs:
private static void InlinesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is ExtendedTextBlock b)) return;
b.Inlines.Clear();
if (e.NewValue is InlineCollection collection)
b.Inlines.AddRange(collection);
if (e.NewValue is Span span)
b.Inlines.AddRange(span.Inlines);
if (e.NewValue is Run run)
b.Inlines.Add(run);
if (e.NewValue is string str)
b.Inlines.Add(new Run(str));
}
DataTemplate:
<DataTemplate>
<controls:ExtendedTextBlock InlineContent="{Binding}" />
</DataTemplate>
Label:
<dxlc:LayoutItem.Label>
<Span>
<Run>Right (R</Run>
<Run Typography.Variants="Subscript">R</Run>
<Run>)</Run>
</Span>
</dxlc:LayoutItem.Label>
This works fine for regular text (strings) but when I set a Span as my label's content, then I get the following exception:
System.Windows.Markup.XamlParseException: 'Collection was modified; enumeration operation may not execute.'
Inner Exception:
InvalidOperationException: Collection was modified; enumeration operation may not execute.
This occurs in line b.Inlines.AddRange(span.Inlines). Why so? I don't understand which collection changes.
Binding directly to Text does not work. Then I only see 'System.Documents.Text.Span` but not the span actually being rendered.

No idea why that happens, but copying Span.Inlines to a new collection solves the problem:
using System.Linq;
...
b.Inlines.AddRange(span.Inlines.ToList());

Related

How to find clicked UIElement child

I would like to get the clicked UIElement's child element that is button. Maybe there is simple and short solution for this? I have searched for this answer awhile, but could't find solution that would be easy to understand and use. I will appreciate any kind of help related to this question.
Code that i have right now:
private new void MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (sender == (sender as UIElement))
{
//TODO: getting controls name that is placed inside clicked UIElement
}
}
Edit:
Wanted to mention that UIElement is ContentControl that is using ResourceDictionary template.
My xaml code looks something like this
<ContentControl Style="{StaticResource DesignerItemStyle}">
<Button x:Name="btnAdd" Content="add function" IsHitTestVisible="True"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
</ContentControl>
There are two properties in MouseButtonEventArgs which you can leverage for this purpose
Source
This property contains reference to the object that raised the event. example Button etc
OriginalSource
the original reporting source as determined by pure hit testing, before any possible Source adjustment by a parent class, which may have been done to flatten composited element trees. example a Rectangle, Border or any template element inside the Button.
you can retrieve the Name for the element by casting OriginalSource to FrameworkElement or more appropriate
if the OriginalSource is not the desired element then you can retrieve the Logical parent of OriginalSource and that is more likely to be the desired element and retrieving Name remain same as above.
retrieve logical parent example
LogicalTreeHelper.GetParent(e.OriginalSource as DependencyObject);

Wpf Richttextbox Custom Validation

I need some advanced validation in WPF Richtextbox for flowdocuments, something like:
a) formatting can be applied only to the whole paragraph
b) no spans are allowed
c) these rules also need to be applied for Text pasted from clipboard.
What is the best way to do it?
Add an event handler to the textchanged event and apply whatever formatting you need done there. The event will fire no matter how the text is changed in the textbox (pasted via clipboard/entered from keyboard).
<RichTextbox x:Name="myTextbox" TextChanged="myTextbox_TextChanged"/>
private void myTextbox_TextChanged(object sender, EventArgs e)
{
//Apply formatting here
}
Edit: Alternatively if you're text is bound to some sort of datasource, you could implement data validation on the binding which will highlight the textbox red and ensure the users enters the desired input.
<RichTextbox x:Name="myTextbox" Text="{Binding TextSource, ValidatesOnExceptions=True}"/>
In the setter of the TextSource property you would throw an exception if the data entered does not meet your requirements.

How to get x:Name value runtime

I got:
<ListView.View GridViewColumnHeader.Click="ColumnHeaderClick">
<GridView>
<GridViewColumn x:Name="Col" Header="Item">
private void ColumnHeaderClick(object sender, RoutedEventArgs e)
{
GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader;
}
Now, how to get the x:Name value of GridViewColumn in the method? I can't put 'Name' property for the column in xaml, and it comes like empty string in runtime. Although I am able to get the header, still need to get x:Name value.
When you use the x:Name syntax on an element that isn't a FrameworkElement or FrameworkContentElement, it registers the element with a NameScope. Unfortunately, you can't retrieve the name for an element, the lookup only works the other way around.
If you need to pass additional information about the DataGridColumn, a custom attached property would be an easy way of doing it.
More information about x:Name can be found on MSDN. Also, the NameScope documentation describes its behavior.
You can leverage reflection to grab the value with:
GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader;
String xName = (String)headerClicked.getType().GetProperty("Name").GetValue(headerClicked, null);

WPF DataTemplate: How to create a tooltip just-in-time?

I am using DataTemplates to render items in an ItemsControl. I want to show a tooltip for each item. If I use a binding such as ToolTip="{Binding MyToolTip,Mode=OneWay}", WPF gets the tooltip once at the beginning and does not update the tooltip when it is opened.
My items implement INotifyPropertyChanged, so in principle I could generate change notifications for MyToolTip. The problem is, the tooltip is produced based on many pieces of information in the underlying model. These pieces of information change frequently and it would be both cumbersome and inefficient to generate change notifications for the MyToolTip property. Besides, I do not want tooltips for ALL items to be produced initially. Instead I would like to force a fresh tooltip to be generated when the tooltip is opened. How can I do it?
You will have to use a little code-behind, but it isn't that bad.
<object ToolTip="{Binding MyToolTip, Mode=OneWay}" ToolTipOpening="MyToolTip_Opening" />
In code-behind
private void MyToolTip_Opening(object sender, ToolTipEventArgs e)
{
DependencyObject depObj = sender as DependencyObject;
if (depObj == null) return;
BindingExpression be = BindingOperations.GetBindingExpression(depObj, FrameworkElement.ToolTipProperty);
if (be != null) be.UpdateTarget();
}

WPF Databind Before Saving

In my WPF application, I have a number of databound TextBoxes. The UpdateSourceTrigger for these bindings is LostFocus. The object is saved using the File menu. The problem I have is that it is possible to enter a new value into a TextBox, select Save from the File menu, and never persist the new value (the one visible in the TextBox) because accessing the menu does not remove focus from the TextBox. How can I fix this? Is there some way to force all the controls in a page to databind?
#palehorse: Good point. Unfortunately, I need to use LostFocus as my UpdateSourceTrigger in order to support the type of validation I want.
#dmo: I had thought of that. It seems, however, like a really inelegant solution for a relatively simple problem. Also, it requires that there be some control on the page which is is always visible to receive the focus. My application is tabbed, however, so no such control readily presents itself.
#Nidonocu: The fact that using the menu did not move focus from the TextBox confused me as well. That is, however, the behavior I am seeing. The following simple example demonstrates my problem:
<Window x:Class="WpfApplication2.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<ObjectDataProvider x:Key="MyItemProvider" />
</Window.Resources>
<DockPanel LastChildFill="True">
<Menu DockPanel.Dock="Top">
<MenuItem Header="File">
<MenuItem Header="Save" Click="MenuItem_Click" />
</MenuItem>
</Menu>
<StackPanel DataContext="{Binding Source={StaticResource MyItemProvider}}">
<Label Content="Enter some text and then File > Save:" />
<TextBox Text="{Binding ValueA}" />
<TextBox Text="{Binding ValueB}" />
</StackPanel>
</DockPanel>
</Window>
using System;
using System.Text;
using System.Windows;
using System.Windows.Data;
namespace WpfApplication2
{
public partial class Window1 : Window
{
public MyItem Item
{
get { return (FindResource("MyItemProvider") as ObjectDataProvider).ObjectInstance as MyItem; }
set { (FindResource("MyItemProvider") as ObjectDataProvider).ObjectInstance = value; }
}
public Window1()
{
InitializeComponent();
Item = new MyItem();
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(string.Format("At the time of saving, the values in the TextBoxes are:\n'{0}'\nand\n'{1}'", Item.ValueA, Item.ValueB));
}
}
public class MyItem
{
public string ValueA { get; set; }
public string ValueB { get; set; }
}
}
I found that removing the menu items that are scope depended from the FocusScope of the menu causes the textbox to lose focus correctly. I wouldn't think this applies to ALL items in Menu, but certainly for a save or validate action.
<Menu FocusManager.IsFocusScope="False" >
Assuming that there is more than one control in the tab sequence, the following solution appears to be complete and general (just cut-and-paste)...
Control currentControl = System.Windows.Input.Keyboard.FocusedElement as Control;
if (currentControl != null)
{
// Force focus away from the current control to update its binding source.
currentControl.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
currentControl.Focus();
}
This is a UGLY hack but should also work
TextBox focusedTextBox = Keyboard.FocusedElement as TextBox;
if (focusedTextBox != null)
{
focusedTextBox.GetBindingExpression(TextBox.TextProperty).UpdateSource();
}
This code checks if a TextBox has focus... If 1 is found... update the binding source!
Suppose you have a TextBox in a window, and a ToolBar with a Save button in it. Assume the TextBox’s Text property is bound to a property on a business object, and the binding’s UpdateSourceTrigger property is set to the default value of LostFocus, meaning that the bound value is pushed back to the business object property when the TextBox loses input focus. Also, assume that the ToolBar’s Save button has its Command property set to ApplicationCommands.Save command.
In that situation, if you edit the TextBox and click the Save button with the mouse, there is a problem. When clicking on a Button in a ToolBar, the TextBox does not lose focus. Since the TextBox’s LostFocus event does not fire, the Text property binding does not update the source property of the business object.
Obviously you should not validate and save an object if the most recently edited value in the UI has not yet been pushed into the object. This is the exact problem Karl had worked around, by writing code in his window that manually looked for a TextBox with focus and updated the source of the data binding. His solution worked fine, but it got me thinking about a generic solution that would also be useful outside of this particular scenario. Enter CommandGroup…
Taken from Josh Smith’s CodeProject article about CommandGroup
Simple solution is update the Xaml code as shown below
<StackPanel DataContext="{Binding Source={StaticResource MyItemProvider}}">
<Label Content="Enter some text and then File > Save:" />
<TextBox Text="{Binding ValueA, UpdateSourceTrigger=PropertyChanged}" />
<TextBox Text="{Binding ValueB, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
I've run into this issue and the best solution I've found was to change the focusable value of the button (or any other component such as MenuItem) to true:
<Button Focusable="True" Command="{Binding CustomSaveCommand}"/>
The reason it works, is because it forces the button to get focused before it invokes the command and therefore makes the TextBox or any other UIElement for that matter to loose their focus and raise lost focus event which invokes the binding to be changed.
In case you are using bounded command (as I was pointing to in my example), John Smith's great solution won't fit very well since you can't bind StaticExtension into bounded property (nor DP).
Have you tried setting the UpdateSourceTrigger to PropertyChanged? Alternatively, you could call the UpdateSOurce() method, but that seems like a bit overkill and defeats the purpose of TwoWay databinding.
Could you set the focus somewhere else just before saving?
You can do this by calling focus() on a UI element.
You could focus on whatever element invokes the "save". If your trigger is LostFocus then you have to move the focus somewhere. Save has the advantage that it isn't modified and would make sense to the user.
Since I noticed this issue is still a pain in the ass to solve on a very generic way, I tried various solutions.
Eventually one that worked out for me:
Whenever the need is there that UI changes must be validated and updated to its sources (Check for changes upon closeing a window, performing Save operations, ...), I call a validation function which does various things:
- make sure a focused element (like textbox, combobox, ...) loses its focus which will trigger default updatesource behavior
- validate any controls within the tree of the DependencyObject which is given to the validation function
- set focus back to the original focused element
The function itself returns true if everything is in order (validation is succesful) -> your original action (closeing with optional asking confirmation, saveing, ...) can continue. Otherwise the function will return false and your action cannot continue because there are validation errors on one or more elements (with the help of a generic ErrorTemplate on the elements).
The code (validation functionality is based on the article Detecting WPF Validation Errors):
public static class Validator
{
private static Dictionary<String, List<DependencyProperty>> gdicCachedDependencyProperties = new Dictionary<String, List<DependencyProperty>>();
public static Boolean IsValid(DependencyObject Parent)
{
// Move focus and reset it to update bindings which or otherwise not processed until losefocus
IInputElement lfocusedElement = Keyboard.FocusedElement;
if (lfocusedElement != null && lfocusedElement is UIElement)
{
// Move to previous AND to next InputElement (if your next InputElement is a menu, focus will not be lost -> therefor move in both directions)
(lfocusedElement as UIElement).MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous));
(lfocusedElement as UIElement).MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
Keyboard.ClearFocus();
}
if (Parent as UIElement == null || (Parent as UIElement).Visibility != Visibility.Visible)
return true;
// Validate all the bindings on the parent
Boolean lblnIsValid = true;
foreach (DependencyProperty aDependencyProperty in GetAllDependencyProperties(Parent))
{
if (BindingOperations.IsDataBound(Parent, aDependencyProperty))
{
// Get the binding expression base. This way all kinds of bindings (MultiBinding, PropertyBinding, ...) can be updated
BindingExpressionBase lbindingExpressionBase = BindingOperations.GetBindingExpressionBase(Parent, aDependencyProperty);
if (lbindingExpressionBase != null)
{
lbindingExpressionBase.ValidateWithoutUpdate();
if (lbindingExpressionBase.HasError)
lblnIsValid = false;
}
}
}
if (Parent is Visual || Parent is Visual3D)
{
// Fetch the visual children (in case of templated content, the LogicalTreeHelper will return no childs)
Int32 lintVisualChildCount = VisualTreeHelper.GetChildrenCount(Parent);
for (Int32 lintVisualChildIndex = 0; lintVisualChildIndex < lintVisualChildCount; lintVisualChildIndex++)
if (!IsValid(VisualTreeHelper.GetChild(Parent, lintVisualChildIndex)))
lblnIsValid = false;
}
if (lfocusedElement != null)
lfocusedElement.Focus();
return lblnIsValid;
}
public static List<DependencyProperty> GetAllDependencyProperties(DependencyObject DependencyObject)
{
Type ltype = DependencyObject.GetType();
if (gdicCachedDependencyProperties.ContainsKey(ltype.FullName))
return gdicCachedDependencyProperties[ltype.FullName];
List<DependencyProperty> llstDependencyProperties = new List<DependencyProperty>();
List<FieldInfo> llstFieldInfos = ltype.GetFields(BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Static).Where(Field => Field.FieldType == typeof(DependencyProperty)).ToList();
foreach (FieldInfo aFieldInfo in llstFieldInfos)
llstDependencyProperties.Add(aFieldInfo.GetValue(null) as DependencyProperty);
gdicCachedDependencyProperties.Add(ltype.FullName, llstDependencyProperties);
return llstDependencyProperties;
}
}
The easiest way is to set the focus somewhere.
You can set the focus back immediately, but setting the focus anywhere will trigger the LostFocus-Event on any type of control and make it update its stuff:
IInputElement x = System.Windows.Input.Keyboard.FocusedElement;
DummyField.Focus();
x.Focus();
Another way would be to get the focused element, get the binding element from the focused element, and trigger the update manually. An example for TextBox and ComboBox (you would need to add any control type you need to support):
TextBox t = Keyboard.FocusedElement as TextBox;
if ((t != null) && (t.GetBindingExpression(TextBox.TextProperty) != null))
t.GetBindingExpression(TextBox.TextProperty).UpdateSource();
ComboBox c = Keyboard.FocusedElement as ComboBox;
if ((c != null) && (c.GetBindingExpression(ComboBox.TextProperty) != null))
c.GetBindingExpression(ComboBox.TextProperty).UpdateSource();
What do you think about this? I believe I've figured out a way to make it a bit more generic using reflection. I really didn't like the idea of maintaining a list like some of the other examples.
var currentControl = System.Windows.Input.Keyboard.FocusedElement;
if (currentControl != null)
{
Type type = currentControl.GetType();
if (type.GetMethod("MoveFocus") != null && type.GetMethod("Focus") != null)
{
try
{
type.GetMethod("MoveFocus").Invoke(currentControl, new object[] { new TraversalRequest(FocusNavigationDirection.Next) });
type.GetMethod("Focus").Invoke(currentControl, null);
}
catch (Exception ex)
{
throw new Exception("Unable to handle unknown type: " + type.Name, ex);
}
}
}
See any problems with that?
Using BindingGroup will help to understand and mitigate this kind of problem.
Sometimes we consider to apply MVVM model against WPF data bindings.
For example, we consider about mail's subject property:
<TextBox x:Name="SubjectTextBox" Text="{Binding Subject}" />
TextBox SubjectTextBox is on side of View.
The bound property like ViewModel.Subject will belong to ViewModel.
The problem is that changes remain to View in this case.
When we close the WPF window, WPF TextBox won't loose focus on window close.
It means data binding won't perform writing back, and then changes are lost silently.
Introducing of BindingGroup helps to control whether we should apply changes: from View to ViewModel.
BindingGroup.CommitEdit(); will ensure apply changes of direction View → ViewModel
BindingGroup.CancelEdit(); will ensure to discard changes on View.
If you don't call neither, changes are lost silently!
In the following sample, we attach RibbonWindow_Closing event handler so that we can deal with this case of problem.
XAML:
<R:RibbonWindow Closing="RibbonWindow_Closing" ...>
<FrameworkElement.BindingGroup>
<BindingGroup />
</FrameworkElement.BindingGroup>
...
</R:RibbonWindow>
C#
private void RibbonWindow_Closing(object sender, CancelEventArgs e) {
e.Cancel = !NeedSave();
}
bool NeedSave() {
if (!BindingGroup.CommitEdit()) {
// There may be validation error.
return false; // changes this to true to allow closing.
}
// Insert your business code to check modifications.
// return true; if Saved/DontSave/NotChanged
// return false; if Cancel
}
It should work.

Resources