WPF Binding and Why you should write defensive code.

I’m overriding equals and implementing IEquatable on some of my objects and bind them as an ObservableCollection to the UI. Here is a sample: (ugly code do not use) <Window x:Class=“BindingToItemsWithIEquality.MainWindow” xmlns=“http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x=“http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local=“clr-namespace:BindingToItemsWithIEquality” Title=“MainWindow” Height=“350” Width=“525” > <Window.DataContext> <local:SomeContextWithCollection/> </Window.DataContext> <StackPanel> <ListBox DisplayMemberPath=“Name” ItemsSource="{Binding Items}”/> <Button Click=“Button_Click”>clear</Button> </StackPanel> </Window> //code behind private void Button_Click(object sender, RoutedEventArgs e) { (this.DataContext as SomeContextWithCollection).Items.Clear(); } public class SomeContextWithCollection { public ObservableCollection<SomeIEqutable> Items { get; set; } public SomeContextWithCollection() { Items = new ObservableCollection<SomeIEqutable>(); Items.Add(new SomeIEqutable() { Name = “1” }); Items.Add(new SomeIEqutable() { Name = “2” }); } } public class SomeIEqutable : IEquatable<SomeIEqutable> { public string Name { get; set; } public override bool Equals(object obj) { if (obj == null) { return false; } return Equals((SomeIEqutable)obj); } public bool Equals(SomeIEqutable other) { if (object.ReferenceEquals(this, other)) { return true; } return Name == other.Name; } public override int GetHashCode() { return Name.GetHashCode(); } } When calling collection.Clear() I get an invalid cast inside my equals method, when trying to cast to SomeIEquatable. This is pretty strange, object is not null and not SomeIEquatlabe, how did it get to my Equals? The answer is WPF, when working with binding and clearing a bounded collection WPF will compare his internal new MSInternal.NamedObject(named DisconnectedItem) to your SomeIEquatable object and will fail if you try to implicitly cast it to your type. The simple solution is to use the “as” keyword instead of cast. If my code didn’t smell from the start, I would never got to this dark place. But I’m glad it happened, now I have another excuse to write defensive code.

January 5, 2011 · 2 min · Chen Kinnrot

What do you think?

About a year ago I asked the following question This week I got one more answer and I wanna ask you guys what do you think is the best practice?

January 5, 2011 · 1 min · Chen Kinnrot

Simple way to avoid hard coded strings in xaml

Hard coded strings are annoying, In XAML, we have a lot of cases of hard coded strings. Here is a simple way of implementing static naming class, and use it instead of hard coded strings. Suppose this is my xaml: <Window x:Class=“How.MainWindow” xmlns=“http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x=“http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local=“clr-namespace:How” Title=“MainWindow” Height=“350” Width=“525”> <Window.Resources> <Style TargetType="{x:Type Button}” x:Key=“LazyGuyMeaninglessName”> <Setter Property=“Margin” Value=“30”/> <Setter Property=“Height” Value=“30”/> <Setter Property=“Width” Value=“200”/> </Style> </Window.Resources> <StackPanel> <Button Click=“Button_Click”>Click me to activate my style</Button> <Button Style="{DynamicResource LazyGuyMeaninglessName}”/> </StackPanel> </Window> This is code behind: private void Button_Click(object sender, RoutedEventArgs e) { var button = sender as Button; if (button != null) { button.Style = (Style)this.FindResource(“LazyGuyMeaninglessNameWithMistake”); } } I have a mistake in my code behind, and the program will crash, not so fun, and not simple to test this kind of stuff. There is a very simple solution, Lets define this class: public static class StyleNames { public static string ButtonStyleName = “Some Hard To write style name”; } The benefits of using this class instead of hard coded strings are: No need to avoid long meaningful names, cause you have auto complete built in the IDE.The obvious: avoid type mistakes, and unexpected crashes.Make your programmers less lazy, they’ll be able to change the resource name in a single place, and even his member name if needed, VS will rename it in all references and in XAML(VS 2010) (with a “Ctrl + .” after editing the member name).If the style name is not readonly(like in my sample), I’m sure there is a simple way to support theming and dynamic style changing, by just assigning new names for all the resource names inside StyleNames class, and telling the app to do something that will reload all styles, I’m not sure about it, so don’t count on it.No crashes of “could not find resource bla bla”. Here is the code after the use of static class: <Window x:Class=“How.MainWindow” xmlns=“http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x=“http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local=“clr-namespace:How” Title=“MainWindow” Height=“350” Width=“525”> <Window.Resources> <Style TargetType="{x:Type Button}” x:Key="{x:Static local:StyleNames.ButtonStyleName}"> <Setter Property=“Margin” Value=“30”/> <Setter Property=“Height” Value=“30”/> <Setter Property=“Width” Value=“200”/> </Style> </Window.Resources> <StackPanel> <Button Click=“Button_Click”>Click me to activate my style</Button> <Button Style="{DynamicResource ResourceKey={x:Static local:StyleNames.ButtonStyleName}}”/> </StackPanel> </Window> private void Button_Click(object sender, RoutedEventArgs e) { var button = sender as Button; if (button != null) { button.Style = (Style)this.FindResource(StyleNames.ButtonStyleName); } } Enjoy :)

January 3, 2011 · 2 min · Chen Kinnrot