Archive for the “C#” Category
Consider a Windows Phone 7 application with a textbox and an ApplicationButton.

UI:
- <Canvas x:Name="ContentGrid" Grid.Row="1" Height="545" Width="480">
- <TextBlock Text="Enter text here" Canvas.Left="6" Canvas.Top="187" />
- <TextBox x:Name="myTextBox" Text="{Binding Test, Mode=TwoWay}" Height="69" Width="480" Canvas.Left="0" Canvas.Top="209" />
- </Canvas>
Backend:
- namespace WindowsPhoneApplication1
- {
- using System;
- using System.ComponentModel;
- using System.Windows.Controls;
- using Microsoft.Phone.Controls;
-
- public partial class MainPage : PhoneApplicationPage, INotifyPropertyChanged
- {
- private string _test;
- // Constructor
- public MainPage()
- {
- this.InitializeComponent();
-
- this.DataContext = this;
- }
-
- public string Test
- {
- get
- {
- return this._test;
- }
- set
- {
- if (value != this._test)
- {
- this._test = value;
- this.PropertyChanged(this, new PropertyChangedEventArgs("Test"));
- }
- }
- }
-
- #region INotifyPropertyChanged Members
-
- public event PropertyChangedEventHandler PropertyChanged;
-
- #endregion
-
- }
- }
The textbox is bound to a property on the backend (two way binding) and when you click the bottom button the text is saved/send/encrypted/whatever.
Now the problem is that clicking the button doesn’t do a UI –> source binding update as it would do with a normal button.

I enter the text ‘test’ on the TextBlock and IMMIDIATLY click the ApplicationButton. I don’t do anything else. This is a common user practice, he changes something and clicks the save/send/whatsoever button.
This is the result:

Check the Watch 1. As you can see the value is still null. The value is not sent to the _test value. How do we solve this?
You can add the following line to the click event handler:
- this.myTextBox.GetBindingExpression(TextBox.TextProperty).UpdateSource();
So the result will look like this:
- private void AppbarButton1Click(object sender, EventArgs e)
- {
- this.myTextBox.GetBindingExpression(TextBox.TextProperty).UpdateSource();
-
- // handle save/send/encrypt/whatever here
- }
There are 3 downsides I think:
- You need to name your TextBlock which (I think) unnecessarily clutters your scope with otherwise unused variables (that’s why we use bindings too!)
- Your UI and ViewModel (in my case) aren’t decoupled 100% anymore. In Windows Phone 7 this is no issue though, since WP7 has no ICommand and I have to couply my UI and ViewModel anyway
- You need to remember to write this line! Which can be quite cumbersome with a lot of application buttons.
And items in a ApplicationBar.MenuItems (ApplicationBarMenuItem) have the same problem. The UI doesn’t push the update to the ViewModel.
I hope this will be fixed in the final version, and I will post this to Microsoft Connect. If anybody has a better solution please feel free to share it.
No Comments »
- static class ExtensionMethods
- {
- public static void Raise<TValue>(this PropertyChangedEventHandler handler, Expression<Func<TValue>> propertySelector)
- {
- var memberExpression = propertySelector.Body as MemberExpression;
-
- if (handler == null || memberExpression == null)
- {
- return;
- }
-
- var sender = ((ConstantExpression)memberExpression.Expression).Value;
- handler(sender, new PropertyChangedEventArgs(memberExpression.Member.Name));
- }
- }
Use this as an extension method like this on a class that implements INotifyPropertyChanged
- class SomeClass : INotifyPropertyChanged
- {
- private string _someProperty;
-
- public string SomeProperty
- {
- get
- {
- return this._someProperty;
- }
- set
- {
- if (value != this._someProperty)
- {
- this._someProperty = value;
- this.PropertyChanged.Raise(() => this.SomeProperty);
- }
- }
- }
-
- public event PropertyChangedEventHandler PropertyChanged;
- }
Good luck
-Kristof
No Comments »
Since MvvmLight exposes it’s own ViewModelBase you cannot use this little script to raise the INotifyPropertyChangedEventHandler, because .NET doesn’t allow you to raise events in derived classes. This is because the compiler generates a private delegate (it’s in VB.NET but that doesn’t matter).
And since the ViewModelBase only exposes a protected RaiseProperty(string propertyName) I cannot use strongly typed reflection.
So I found some code, and rewrote it like this.
Now you can create a class that inherits from ViewModelBase, and make your ViewModels inherit from your just created class.
Now you have a pattern like this:
ViewModelBase <—DefaultViewModel <—MainPageViewModel
And your DefaultViewModel should look like this:
- public abstract class DefaultViewModel : ViewModelBase
- {
- protected void RaisePropertyChanged<TValue>(Expression<Func<TValue>> propertySelector)
- {
- var memberExpression = (propertySelector.Body as MemberExpression);
-
- if (null != memberExpression)
- this.RaisePropertyChanged(memberExpression.Member.Name);
- }
- }
And your MainPageViewModel (for example):
- public class MainPageViewModel : DefaultViewModel
- {
- private decimal _remainingCredits;
-
- /// <summary>
- /// Remaining credits of the current account
- /// </summary>
- public decimal RemainingCredits
- {
- get
- {
- return this._remainingCredits;
- }
-
- set
- {
- if (this._remainingCredits != value)
- {
- this._remainingCredits = value;
-
- this.RaisePropertyChanged(() => RemainingCredits);
- }
- }
- }
- }
You can use the form of RaisePropertyChanged(() => NameOfProperty);
This way, when you rename a variable in your code the refactor engine picks it up and renames it accordingly. (it forget strings
Good luck,
Kristof
No Comments »
Hi all,
I tried to display an icon in my Windows Phone 7 application:
<shell:ApplicationBarIconButton x:Name="appbar_button1" IconUri="/Images/appbar.feature.settings.rest.png" Text="Settings" />
By default, when you add an image to the solution folder it sets the build action as Resource, as shown below:
But when you run the application with the Build Action as Resource you will get a result looking like this:
While I really meant an icon looking like this:
How do we fix it?
Set the Build Action to Content!

And this is the result:

No Comments »
I’ve been stuck on this for a few days.
At the moment, Firefox 3.6.4 (and newer) have a new functionality called ‘Crash protection’, which is quite nice.
For customers.
…
It now runs the plugins in a separate process called ‘plugin-container.exe’ (look in your task manager).

But for developers it’s quite the hassle, since Visual Studio attaches itself to Firefox but NOT to this process. So no more Silverlight debugging for you!
Luckily there are two options for you!
The first option is the most straight forward, but has to be done each time. Use Visual Studio to attach itself to plugin-container.exe, refresh the website, and BAM, you’re up and running!

On the next screen click ‘plugin-container.exe’. There might be 2, if so, select the one with ‘Silverlight’ in the ‘Type’ column:

And hit ‘Attach’.
While this solution is adequate for when you need to debug it one time at a day, but for me, I only debug in Firefox, and when necessary I use Internet Explorer. For that you can go to your ‘about:config’ in Firefox, disable ‘dom.ipc.plugins.enabled.npctrl.dll’ (set it to false).
1 Comment »
I ran into this little problem last week. I had a class with some properties and they were implemented like this:
class Foo
{
private int _bar;
public int Bar
{
get
{
return this._bar;
}
set
{
this._bar = value;
this.DoSomeThing();
}
}
private void DoSomeThing()
{
/* blah */
}
}
Setting the value of Bar to something triggers DoSomeThing, whether the value of _bar is changed or not. (setting _bar to 5 when it is 5 will still trigger DoSomeThing, for example a UI refresh).
You can avoid this by doing this in your property:
class Foo
{
private int _bar;
public int Bar
{
get
{
return this._bar;
}
set
{
if (this._bar != value)
{
this._bar = value;
DoSomeThing();
}
}
}
private void DoSomeThing()
{
/* blah */
}
}
This makes sure that you don’t execute the value when the value hasn’t changed.
This occurs in particular in Excel when trying to update the CurrentPageName of a DataField in a PivotTable. I need to check if the value has changed, and then, if it has changed, assign it.
No Comments »
I created this class to make life a little bit easier for me.
You are free to use it as you wish!
How to use:
Override this class, override ReleaseManaged() and ReleaseUnmanaged() with the appropriate code, and you are good to go.
namespace SuperDisposeImplementation
{
using System;
/// <summary>
/// Override this class for easy releasing of managed and unmanaged code.
/// </summary>
/// <remarks>
/// By Kristof Mattei
/// Use as you wish
/// I don't hold the copyright
/// Combined from code I found everywhere.
/// </remarks>
public abstract class SuperDispose : IDisposable
{
/// <summary>
/// True if managed resources are already cleaned up, false if not
/// </summary>
private bool _disposed;
#region IDisposable Members
/// <summary>
/// Implementation of IDisposable.Dispose(). Don't make virtual
/// </summary>
public void Dispose()
{
this.Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
#endregion
/// <summary>
/// Dispose(bool disposing) executes in two distinct scenarios.
/// If disposing equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed.
/// If disposing equals false, the method has been called by the
/// runtime from inside the finalizer and you should not reference
/// other objects. Only unmanaged resources can be disposed.
/// </summary>
/// <param name="disposing">True when called from the Dispose, false when called from the ~. Don't call yourself</param>
private void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (!this._disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if (disposing)
{
this.ReleaseManaged();
}
// Dispose unmanaged resources.
this.ReleaseUnmanaged();
// disposing has been done, make sure we don't dispose the managed ones again.
this._disposed = true;
}
}
/// <summary>
/// Override this method, and release unmanaged resources in that method
/// </summary>
protected abstract void ReleaseUnmanaged();
/// <summary>
/// Override this method, and release managed resources in that method
/// </summary>
protected abstract void ReleaseManaged();
/// <summary>
/// Use C# destructor syntax for finalization code.
/// This destructor will run only if the Dispose method
/// does not get called.
/// It gives your base class the opportunity to finalize.
/// Do not provide destructors in types derived from this class.
/// </summary>
~SuperDispose()
{
// make sure we don't dispose managed resources, hence the false
// this is because we can't control the called order of
this.Dispose(false);
}
}
}
No Comments »
I’ve been a huge fan of LINQ to SQL. But EF 3.5 (first release) didn’t quite do it for me. I didn’t like the lack of support for foreign keys, no Single() LINQ support,

An example of lack of foreign keys:
using(NorthwindEntities northwindEntities = new NorthwindEntities())
{
Product p = new Product()
{
Category = northwindEntities.Categories.Where(c => c.CategoryID == 1).First,
ProductName = "French fries",
UnitPrice = 20,
Discontinued = false,
QuantityPerUnit = "1 kg bag",
Supplier = northwindEntities.Suppliers.Where(s => s.SupplierID == 1).First
};
northwindEntities.AddToProducts(p);
northwindEntities.SaveChanges();
}
As you can see you need to fetch the category and the Supplier seperatly. You can’t just do CategoryID = 1
But when we launch the wizard for EF 4.0 we get this:

Which results in this:
using(NorthwindEntities northwindEntities = new NorthwindEntities())
{
Product p = new Product()
{
CategoryID = 1,
ProductName = "French fries",
UnitPrice = 20,
Discontinued = false,
QuantityPerUnit = "1 kg bag",
SupplierID = 1
};
northwindEntities.AddToProducts(p);
northwindEntities.SaveChanges();
}
And there is Single support!
using(NorthwindEntities ne = new NorthwindEntities())
{
var result = ne.Suppliers.Where(sup => sup.SupplierID == 1).Single();
}
So it just got a little more mature.
I’m hoping to be able to test it (and use it!) more in the future and new projects
Hope it helps
-Kristof
3 Comments »
A little introduction: I’m working on some legacy VB.NET & Excel project. Pretty old stuff, quite the challenge of getting through the code. I’ve discovered multiple things about VB.NET which I didn’t knew (like the Microsoft.VisualBasic namespace, late binding, Option Strict).
The code I’m working with is cluttered with these kinds of abominations to the .NET framework. The Microsoft.VisualBasic is purely there for legacy VBA developers so that they can easily transfer to VB.NET.
But that doesn’t mean you need to use it in new projects (vbNullString? C’mon…)
I think that this namespace shouldn’t be offered by default anymore in new VB.NET projects. It should be there to merely quickly convert old VBA projects to .NET.
Late binding is another thing which I truly hate. It gets compiled to a bunch of reflection calls which make your code more error prone (no compiler checking!). Although I’ve managed to cast the System.__ComObject to it’s corresponding interface most of the time I had to resort to reflection one time myself (shame shame).
And finally there is this problem of cluttered code, for some reason, when I look at VB.NET code there is SO much text and all the essence get’s lost! While the C# code is so clean.
I will write a post about cleaning up With statements + best practices for nested With Statements from VB.NET code pretty soon.
No Comments »
Ever wanted to have a multi column ListView in WPF? It’s not that hard once you get to know WPF.
We take a ListView and set the ItemsPanel to UniformGrid:
<Window x:Class="ColumnTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<ListView x:Name="MyList">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="3" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<Label Content="{Binding}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Window>
And the backend code:
using System.Windows;
namespace ColumnTest
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
for (int x = 0; x <= 100; x++)
{
this.MyList.Items.Add(x);
}
}
}
}
Which results in:

No Comments »
|