Archive for the ‘Silverlight’ Category

The DataGrid and the “Input string is not in a correct format” message in Silverlight

Sunday, December 20th, 2009

If you play around with the DataGrid in Silverlight and try some scenarios, maybe you come around the FormatException with the Message “Input String is not in a correct format”. You get this Exception if your Data-Object e.g. has a Property of type int and the user enters some characters in the DataGrid. The Exception doesn’t come up, instead the DataGrid shows it as a validation error. Let’s look at an example. Image you’ve a very simple Person-class containing a FirstName-Property of type string and an Age-Property of type int:

public class Person : INotifyPropertyChanged
{
  private int? _age;
  private string _firstName;
  public string FirstName
  {
    get { return _firstName; }
    set
    {
      _firstName = value;
      Changed("FirstName");
    }
  }

  public int? Age
  {
    get { return _age; }
    set
    {
      _age = value;
      Changed("Age");
    }
  }

  private void Changed(string propertyName)
  {
    if (PropertyChanged != null)
      PropertyChanged(this,
        new PropertyChangedEventArgs(propertyName));
  }

  public event PropertyChangedEventHandler PropertyChanged;
}

Now let’s fill up a List with some Test-Persons and add that list to the DataContext of your page:

public MainPage()
{
  InitializeComponent();
  this.DataContext = new List<Person> {
    new Person{ FirstName="Thomas",Age=29},
    new Person{ FirstName="Julia",Age=27},
    new Person{ FirstName="Ben",Age=1},
  };
}

No in the XAML-File of your MainPage a DataGrid could be defined like below. Notice the ItemsSource-Property that is bound to the DataContext:

<my:DataGrid ItemsSource="{Binding}"
             AutoGenerateColumns="False">
  <my:DataGrid.Columns>
    <my:DataGridTextColumn Header="FirstName"
                           Binding="{Binding FirstName}"/>
    <my:DataGridTextColumn Header="Age"
                           Binding="{Binding Age}"/>
  </my:DataGrid.Columns>
</my:DataGrid>

When the User now enters a string as Age, the FormatException is raised before the Property is updated and the Message of the FormatException is displayed in the DataGrid:

image

Now the question is, where to change this string. The DataGrid has a BindingValidationError-Event, but there you have only read access to the FormatException and the Errormessage. In the Property itself you can’t do anything, because the Exception is thrown before the Age-Property is set.

The solution is to define a Property special for Display in the Person-class. Normally you would create a ViewModel that encapsulates the Person-class and contains the additional property. In my case I implement the Property directly in the Person-class. I call it AgeDisplay-Property. Inside that property you can then throw your own FormatException with your special text. My Person-class now looks like this:

public class Person : INotifyPropertyChanged
{
  private int? _age;
  private string _firstName;
  public string FirstName
  {
    get { return _firstName; }
    set
    {
      _firstName = value;
      Changed("FirstName");
    }
  }

  public int? Age
  {
    get { return _age; }
    set
    {
      _age = value;
      Changed("Age");
      Changed("AgeDisplay");
    }
  }

  public string AgeDisplay
  {
    get { return Age.ToString(); ; }
    set
    {
      if (value == null)
      {
        Age = null;
        return;
      }
      int result;
      if (int.TryParse(value, out result))
      {
        Age = result;
      }
      else
      {
        throw new FormatException("Age must be a number. "
                        + " Characters are not allowed.");
      }
    }
  }

  private void Changed(string propertyName)
  {
    if (PropertyChanged != null)
      PropertyChanged(this,
        new PropertyChangedEventArgs(propertyName));
  }

  public event PropertyChangedEventHandler PropertyChanged;
}

No you simple bind the DataGrid’s Column to AgeDisplay instead of Age:

<my:DataGrid ItemsSource="{Binding}"
             AutoGenerateColumns="False">
  <my:DataGrid.Columns>
    <my:DataGridTextColumn Header="FirstName"
                           Binding="{Binding FirstName}"/>
    <my:DataGridTextColumn Header="Age"
                           Binding="{Binding AgeDisplay}"/>
  </my:DataGrid.Columns>
</my:DataGrid>

When the user now enters a string into the Age-Column, the text of the FormatException thrown in the AgeDisplay-Property is displayed:

image

Great news for Silverlight on Linux

Saturday, December 19th, 2009

The Silverlight-Plugin runs per default on Windows and MacOs. For Linux-Machines there’s an opensource implementation driven by Microsoft and Novell called Moonlight.

While Silverlight is currently in Version 3 available and Version 4 (already in beta) is expected for spring next year, the Moonlight implementation was only availabe in Version 1. And Version 1 means no C#, no CLR, just hacking JavaScript and XAML. But two days ago the big step for Silverlight on Linux was done and Moonlight reached version 2. It’s available for download: http://www.mono-project.com/Moonlight

I think with reaching that level from “only-JavaScript” to the managed C#-API, the future releases of Moonlight will be more closely to the Silverlight-releases for Windows.

Silverlight 4 – How to focus a TextBox that is contained in your Custom Control on Startup

Thursday, December 17th, 2009

Focusing a TextBox that’s inside a Custom Control isn’t so easy at startup of your application. Let me explain the problem that is also discussed on http://forums.silverlight.net/forums/t/151235.aspx. Imagine you’ve created a custom control that has a TextBox as Part-element. The Style that sets the Template would look like this:

<Style TargetType="local:SimpleControl">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate  TargetType="local:SimpleControl">
        <Border Background="{TemplateBinding Background}"
          BorderBrush="{TemplateBinding BorderBrush}"
          BorderThickness="{TemplateBinding BorderThickness}">
          <TextBox x:Name="PART_Text" Margin="10"></TextBox>
        </Border>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

You get the TextBox from the Template in the OnApplyTemplate-Method

public override void OnApplyTemplate()
{
  base.OnApplyTemplate();
  _partTextBox = this.GetTemplateChild("PART_Text") as TextBox;
}

Now imaginge you want to focus your SimpleControl in the constructor of your MainPage like below:

public MainPage()
{
  InitializeComponent();
  HtmlPage.Plugin.Focus();
  yourControl.Focus();
}

The Problem that occurs is that the OnApplyTemplate-Method is called after the Focus-Method. So you don’t have the TextBox defined in your Template. The Solution is very easy. Just hide the Focus-Method from the base-class and set a flag. But keep in mind that this won’t work if you store your SimpleControl in a variable of type Control, cause then no polymorphic call is made to the Focus-Method defined in SimpleControl. Here a sample implementation:

public class SimpleControl : Control
{
  private bool _applyFocusToPartTextBox;
  private TextBox _partTextBox;
  public SimpleControl()
  {
    this.DefaultStyleKey = typeof(SimpleControl);
  }
  public override void OnApplyTemplate()
  {
    base.OnApplyTemplate();
    _partTextBox = this.GetTemplateChild("PART_Text") as TextBox;
    if (_partTextBox != null)
    {
      if (_applyFocusToPartTextBox)
        _partTextBox.Focus();
    }
    _applyFocusToPartTextBox = false;
  }
  public new bool Focus()
  {
    if (_partTextBox == null)
    {
      _applyFocusToPartTextBox = true;
      return true;
    }
    return base.Focus();
  }
}

How to supress the Alt-Key in Silverlight’s TextBox

Tuesday, December 1st, 2009

You can restrict the input-values in Silverlight’s TextBox by handling the KeyDown-Event. But the KeyDown-Event isn’t fired if the user enters a key by pressing e.g. ALT + 123.

Corresponding to the problem mentioned in http://forums.silverlight.net/forums/t/147718.aspx, I’ll show here a short workaround by using the TextChanged and KeyUp-Event of the TextBox. Just use the following snippet, that removes a character that was added by pressing the ALT- and another Key or Key-Combination:

private void TextBox_TextChanged(object sender, TextCh… e)
{
  if (_altWasPressed)
  {
    // remove the added character
    var textBox = ((TextBox)sender);
    var caretPos = textBox.SelectionStart;
    var text = textBox.Text;
    var textStart = text.Substring(0, caretPos - 1);
    var textEnd = "";
    if (caretPos < text.Length)
      textEnd = text.Substring(caretPos, text.Length-caretPos);
    textBox.Text = textStart + textEnd;
    textBox.SelectionStart = caretPos - 1;

    _altWasPressed = false;
  }
}
private bool _altWasPressed;
private void TextBox_KeyUp(object sender, KeyEventArgs e)
{
  _altWasPressed = e.Key == Key.Alt;
}

How to print dynamically created Images in Silverlight 4 Beta

Wednesday, November 25th, 2009

Silverlight 4 supports printing scenarios. It’s quite easy. Just create a PrintDocument instance, handle the PrintPage-Event and call the Print-Method. In the PrintPage-Event set the PageVisual-Property of the PrintPageEventArgs to a UIElement of your choice. If there are more pages, set the HasMorePages-Property of the PrintPageEventArgs to true and the PrintPage-Eventhandler would be called again for the next page.

Below a simple example using a lambda expression. When the Print-Method is called a PrintDialog is displayed to the User, where he can select the printer of his choice. When the PrintDialog was accepted, the PrintPage-Event gets fired and the lambda expression below get’s called. The PageVisual-Property is set to a TextBlock. So that TextBlock with the text “Thoams says…” is printed out.

var pd = new PrintDocument();
pd.PrintPage += (s, e) =>
  {
    e.PageVisual = new TextBlock {Text="Thomas says Hello"};
  };
pd.Print();

Ok, so far so good. As I was working on an example for my upcoming Silverlight 4 book I needed to create an Image-Element on the fly and print this out. And then I noticed that the Image doesn’t appear on the output.

While searching for a solution I found somebody having the same problem in this thread in Microsoft’s Silverlight forums:

http://forums.silverlight.net/forums/t/145680.aspx

So, it seemed it was not my cause, it was a Beta-cause. So let’s look at a workaround. But first look at the bug.

I made a smaller example to reproduce it. View the following code. What do you think is printed on the page?

void PrintButton_Click(object sender, RoutedEventArgs e)
{
  var streamResourceInfo =
    Application.GetResourceStream(
      new Uri("thomas.png", UriKind.Relative));

  var bitmapImage = new BitmapImage();
  bitmapImage.SetSource(streamResourceInfo.Stream);

  var image = new Image
  {
    Width = bitmapImage.PixelWidth,
    Height = bitmapImage.PixelHeight,
    Source = bitmapImage
  };

  var pd = new PrintDocument();
  pd.PrintPage += (s, args) =>
    {
      args.PageVisual = image;
    };
  pd.Print();
}

Right, an Image should be printed on the page. But it isn’t. The page is empty. Well, the next thing I tried was to call Measure, Arrange and UpdateLayout on the Image to force a layout-pass. But anyway, it didn’t work, the printed page is always empty.

When the Image isn’t created on the fly, it works. Define the Image in XAML like this

<Image Source="thomas.png" x:Name="image"/>

and a Print-Method in the Codebehind-File would work like that:

void PrintButton_Click(object sender, RoutedEventArgs e)
{
  var pd = new PrintDocument();
  pd.PrintPage += (s, args) =>
    {
      args.PageVisual = image;
    };
  pd.Print();
}

But we want to print an Image on the fly. So how to do that? One way I found out was to create an ImageBrush and set its ImageSource-Property to the BitmapImage. Use the ImageBrush for a Rectangle’s Fill-Property and print out that Rectangle. So here is some code to dynamically print an image by using an ImageBrush in combination with a Rectangle:

void PrintButton_Click(object sender, RoutedEventArgs e)
{
  var streamResourceInfo =
    Application.GetResourceStream(
      new Uri("thomas.png", UriKind.Relative));

  var bitmapImage = new BitmapImage();
  bitmapImage.SetSource(streamResourceInfo.Stream);

  var imageBrush = new ImageBrush();
  imageBrush.ImageSource = bitmapImage;

  var rectangle = new Rectangle
  {
    Width = bitmapImage.PixelWidth,
    Height = bitmapImage.PixelHeight,
    Fill = imageBrush
  };

  var pd = new PrintDocument();
  pd.PrintPage += (s, args) =>
    {
      args.PageVisual = rectangle;
    };
  pd.Print();
}

And voilà, the output looks like this when printed to my PDFCreator-Printer:

image

[Download the Source]

Cheers Thomas

Silverlight 4 – the first Beta is here

Wednesday, November 18th, 2009

… my expectations about a Major 4.0 release next year may come true: Silverlight 4.0, WPF 4.0, .NET 4.0, Expression Blend 4.0 etc.

Today Microsoft announced Silverlight 4.0 Beta 1 available for download. There are impressing features for business applications like print support, clipboard, Drag’n’Drop or local fileaccess through full trusted Silverlight-Applications. I’m glad the Galileo-Computing team and I decided to publish my upcoming Silverlight-book to version 4.0. More infos about the book soon here: www.thomasclaudiushuber.com/silverlight.

Find all interesting links about the Beta 1 of Silverlight 4.0 on the site below:

http://www.silverlight.net/getstarted/silverlight-4-beta/

Cheers
Thomas

Hey Thomas, what’s coming up next?

Saturday, October 31st, 2009

I’ll give you just a short information of what is coming up next and what I did the last months. Let’s start with the things coming up…

… what’s coming up next:

  • WebTech-Conference – 16th November, Karlsruhe/Germany
    Another talk about datadriven Silverlight-Applications. Meet me at this conference for discussions about WPF, Silverlight, .NET in general, my books and other topics. Find more about the WebTech-conference on webtech
  • Update of the WPF-book to .NET 4.0 and Visual Studio 2010
    The WPF-book was written about .NET 3.5. Next year .NET 4.0 will be released. There are many new things introduced in WPF. The DataGrid- and DatePicker-Control, VisualStateManager, Animation Easing Functions, Layout Rounding and so on. I’m working on an update of the book that will be released next year shortly after the German Visual Studio Release.
  • Writing a german book about Silverlight 4
    Currently I’m working hard on my book about Silverlight 4. I’ve already written about 300 pages. The book will be released next year shortly after the Silverlight 4 release. There are no comments on the Silverlight 4 release, but at PDC in mid-November there’s a session about the Silverlight-Roadmap. Then we’ll know more. So stay tuned. Find more about the upcoming Silverlight-Book on the new silverlight-category on my homepage

… what I did the last months:

  • Silverlight-Articles
    I’ve written six articles about Silverlight for the German dotnet-magazine. Download the articles beside others on www.thomasclaudiushuber.com/articles.php.
  • PrioConference – 28th October, Munich/Germany
    I had a session about datadriven Silverlight-Applications. Find the Details on the new talks-category on my homepage.

So stay tuned. If you’ve any questions, leave a comment or write me an email via the contact-form on my homepage.

Thomas

PrioConference – Slides and Live-Demos & More

Thursday, October 29th, 2009

Thanks to all who visited my Session about building datadriven Business-Applications with Silverlight 3 yesterday at the PrioConference in Munich. I hope you enjoyed it. You can download the Slides here. To get the Live-Demos, please contact me directly via the contact-Form of my homepage and I’ll send them to you.

Yesterday in the evening there was a coding-dojo about the KataPotter-Problem. If you attended the next lines of this post may be interesting for you. With the knowledge of the 2,2,2,1,1-Problem I solved the problem from “zero to hero” today while sitting in the train from Munich to Basel in about 45 Minutes. Really 45 Minutes, even a bit less. The idea to solve the problem has already been in my mind yesterday. Because of that  I couldn’t hardly believe Ralf “Dr. Clean Code” Westphal when he and his colleague Stefan said it would need 4 hours to implement the algorithm. Maybe four hours for santaclaus, but not for me. ;-) I think they exaggerated a little bit with the four hours, because it was already half past ten and everybody was thirsty…

Download my 45-Minutes-not-Refactored-Algorithm (sorry for the method with more than ten lines ;-) ) here. What about your algorithms? How did you solve the problem? Are there more tests for my Application that won’t work like the customer would expect? Any comments and hints are welcome.

So, finally, another PrioConference is over. I enjoyed it, it was a really great event. Thanks to Dagmar, Ralph, Tilman, dotnetpro & Co. and all people behind the scences for the great organization and professionality.

Thoughts of Improvements to Silverlights XAML-Parser

Monday, September 14th, 2009

Those of you, who have already developed with WPF “and” Silverlight might know, that Silverlight contains a different XAML-Parser than WPF does.

Some days ago I read on the blog of Rob Relyea a great post about the XAML-Compilers, which create the g.cs- and (only for WPF) the .baml-Files. Rob is talking about improvements for future versions of the XAML-Compilers. Find the post here:

http://blogs.windowsclient.net/rob_relyea/archive/2009/08/25/msbuild-pipeline-for-wpf-amp-silverlight.aspx

I asked in a comment, what about the XAML-Parsers, and Rob has started a new discussion about that topic (Thanks a lot for that) and quoted my comment. So read on here and then go over to Rob’s post and write your thoughts about improvements of the Silverlight XAML-Parser to the Comments-section of his post:

http://blogs.windowsclient.net/rob_relyea/archive/2009/09/08/silverlight-xaml-developer-experience-issues.aspx

Below I’ll summarize my top 3 features I miss most in Silverlights XAML-Parser. All of them exist in the WPF-XAML-Parser:

1. Direct Content with ContentPropertyAttribute

Support direct Content for all Elements that have a ContentPropertyAttribute set on it’s class-definition. E.g. the following doesn’t work in Silverlight yet.

<Button>OK</Button>

In Silverlight you have to do it this way:

<Button Content="OK"/>

This also means you can’t make use of the ContentPropertyAttribute, if your Content isn’t placed in its own element. Take a look at the Friend-class below.

[ContentProperty("FirstName")]
public class Friend
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
}

In WPF you could write the following which not works in Silverlight:

<local:Friend>
  Mary
</local:Friend>

In Silverlight you have to write it the following way using the Attribut-Syntax, which also works without using the ContentPropertyAttribute:

<local:Friend FirstName="Mary"/>

In Silverlight you could also write it this way, by placing the content in its own element.

<local:Friend/>
  <sys:String>Mary</sys:String>
</local:Friend>

Especially if you create custom classes you want to use in XAML, the ContentPropertyAttribute could be very useful.

2. Support for the XmlnsDefinitionAttribute

Also the XmlnsDefinitionAttribute-class exists in Silverlight, you cannot map your own CLR-namespaces with it. You get an “Unknown Namespace”-Message, if you try to use it. In WPF the Attribute is used on assembly-level like below:

[assembly: XmlnsDefinition(
  "http://www.thomasclaudiushuber.com/xaml/thoughts/2009",
  "Thomas.Xaml.Thoughts")]
[assembly: XmlnsDefinition(
  "http://www.thomasclaudiushuber.com/xaml/thoughts/2009",
  "Thomas.Xaml.Thoughts.Controls")]
[assembly: XmlnsDefinition(
  "http://www.thomasclaudiushuber.com/xaml/thoughts/2009",
  "Thomas.Xaml.Thoughts.Data")]

In XAML all the three CLR-Namespaces above could be mapped to one XML-Namespace by using the specified string:

xmlns:thomas=
"http://www.thomasclaudiushuber.com/xaml/thoughts/2009"

Especially for building librariers consisting of more than one CLR-Namespace, it would be great to support the XmlnsDefinitionAttribute, so that a library developer can map all his CLR-Namespace to one XML-Namespace that is used in XAML. That makes the usage of the libary in XAML very compact.

3. Support some missing Markup Extensions

There are also some missing Markup-Extensions in Silverlight. The following would be very great:

  • x:Static – allows you to reference Static Members from XAML.
  • DynamicResource – references a resource and get’s the changes to the resource. Even if a resource with the same key is defined dynamically on a lower level of the Element Tree, this MarkupExtensions grabs the new one
  • x:Type – create a Type-Object of a specific class in XAML

Other thoughts…

… about Markup Extensions

1. Custom Markup-Extensions

If you dig deeper into Silverlight, you’ll notice that there is no support for Custom Markup Extensions. Some Extensions are integrated into the XAML-Parser, and some implement the IMarkupExtension interface as Reflector shows.

In WPF every Markup Extension inherits from MarkupExtension. So you can create your own one by inheriting also from this class and overwrite its ProvideValue-Method. This would be a great feature for Silverlight 4, but as the base-class isn’t in Silverlight yet, there would be “some” things to change.

2. Visual Studio 2010 Beta 1 Intellisense for Markup Extensions

Visual Studio 2010 Intellisense supports Markup Extensions. But it creates e.g. a StaticResource the following way:

<TextBox Background="{StaticResource ResourceKey=myBrush}" />

In Silverlight specifying the ResourceKey-Property explicit isn’t supported. The upper syntax one matches WPF. In Silverlight you’ve to use the markup Extension this way (which also works in WPF):

<TextBox Background="{StaticResource myBrush}" />

Personally I prefer the last way without specifying the ResourceKey-Property explicitly. Maybe this could be done by the Visual Studio team instead of extend the XAML-Parser of Silverlight.

… about x:Name-Attribut

The x:Name-Attributes allows you to give Elements in XAML a name, and access them via Codebehind-File. While WPF supports all elements to have an x:Name-Attribut, Silverlight only supports those deriving from DependencObject.

Even if most classes derive from DependencObject, naming other classes in XAML would by great.

… about IDictionary

Seems that the Silverlight-XAML-Parser is hard-coded to the ResourceDictionary. In WPF you can initialize every collection that implements IList or IDictionary. In Silverlight you can initialize every collection that implements IList or is a ResourceDictionary. It’s not a big issue, cause most times a dictionary is created in code.

So these are my thoughts and wishes for a new release of a Silverlight XAML-Parser. Thanks for reading and now place your own suggestions into the comments section on robs blog here

Here it is: The UpdateSourceTrigger for PropertyChanged in Silverlight

Friday, July 17th, 2009

Today I’ll show you how to implement a PropertyChanged-UpdateSourceTrigger for Silverlight. In Silverlight a Data Binding can have different UpdateSourceTriggers. An UpdateSourceTrigger specifies, when a TwoWay-DataBinding will update its source with the value of the Target-Property.

In most cases you have a TwoWay-DataBinding on TextBoxes. When the user types something into a TextBox, it should be written back to the underlying Data-Object. The other way, when the underlying Data-Object changes, the TextBox should show the actual value of the bound property.

In this post I’ll focus on the moment of writing the data back to the underlying object. In other words, when the data is updated with the text the user has typed in.

In Silverlight the underlying object is updated after the TextBox has lost its focus. In WPF, the UpdateSourceTrigger-Enum has a Member PropertyChanged. If you set the UpdateSourceTrigger-Property of the Data Binding to that value, the underlying object will be updated everytime the user changes the text. Unfortunately Silverlight doesn’t contain the PropertyChanged-Value in its UpdateSourceTrigger-Enum. It only contains a Default- and a LostFocus-Member. As the name implies, LostFocus will update the source when the TextBox loses its focus. But an Attached Property would do the trick.

When I tried to solve this problem I came across a post of Michael Sync, who showed up a solution with an attached-Property that works by stealing the focus everytime the Text of a TextBox changes, and immediately set it back to the TextBox again. Find his post under http://michaelsync.net/2009/06/10/silverlight-attached-properties-bindingupdatesourcetriggerpropertychanged

As I got deep knowledge about WPFs Binding-Engine, I could produce a solution for Silverlight, and I think I got a similar solution to Michael’s, but my solution is built closer on the binding-engine and doesn’t need a focus-trick. So, some details: Behind each Binding, a BindingExpression does the real work. All you have to do when the Text of the TextBox changes is to get the BindingExpression of the Data Binding and to call its UpdateSource-Method. So my Attached-Property-Class looks like the one below (Feel free to use the source in your projects, but please keep the reference to www.thomasclaudiushuber.com). As it is, it just works for the Text-Property of TextBoxes.

/// <summary>
/// Supports a PropertyChanged-Trigger for DataBindings
/// in Silverlight. Works just for TextBoxes
/// (C) Thomas Claudius Huber 2009
/// http://www.thomasclaudiushuber.com
/// </summary>
public class BindingHelper
{
  public static bool GetUpdateSourceOnChange
    (DependencyObject obj)
  {
    return (bool)obj.GetValue(UpdateSourceOnChangeProperty);
  }

  public static void SetUpdateSourceOnChange
    (DependencyObject obj, bool value)
  {
    obj.SetValue(UpdateSourceOnChangeProperty, value);
  }

  // Using a DependencyProperty as the backing store for ...
  public static readonly DependencyProperty
    UpdateSourceOnChangeProperty =
      DependencyProperty.RegisterAttached(
      "UpdateSourceOnChange",
      typeof(bool),
      typeof(BindingHelper),
      new PropertyMetadata(false, OnPropertyChanged));

  private static void OnPropertyChanged
    (DependencyObject obj,
    DependencyPropertyChangedEventArgs e)
  {
    var txt = obj as TextBox;
    if (txt == null)
      return;
    if((bool)e.NewValue)
    {
      txt.TextChanged += OnTextChanged;
    }
    else
    {
      txt.TextChanged -= OnTextChanged;
    }
  }
  static void OnTextChanged(object sender,
    TextChangedEventArgs e)
  {
    var txt = sender as TextBox;
    if(txt==null)
      return;
    var be = txt.GetBindingExpression(TextBox.TextProperty);
    if (be != null)
    {
      be.UpdateSource();
    }
  }
}

The usage of the BindingHelper-class is very simple. Just add it to your project, insert a matching xmlns to your XAML file that contains the CLR-Namespace the BindingHelper-class is in. When that is done, you can simply set the UpdateSourceOnChange-Property on a TextBox to true, and if the Text-Property is databound, you’ll have a Data Binding that will update its source on every PropertyChange. Like in WPF. :-)

<UserControl ...
    xmlns:local="clr-namespace:BindingHelperExample">
  <Grid x:Name="LayoutRoot">
      ...
    <TextBox Text="{Binding FirstName, Mode=TwoWay}"
    local:BindingHelper.UpdateSourceOnChange="True" />
      ...
    </Grid>
</UserControl>



If this post helped you, please kick it. :-)

kick it on DotNetKicks.com