I am a newbie to WPF/XAML. I would like to get an error message if I bind to the wrong data type in XAML. It seems that XAML wants all binding to be through strings, but there are no error messages if you use an int or double by mistake.
I have found this XAML code here:
<ItemsControl ItemsSource="{Binding Path=PointList}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<!--<TextBox Text="{Binding Path=Xstr, Mode=OneWay}" />-->
<Rectangle Fill="Red" Width="25" Height="25" />
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Canvas.Top" Value="{Binding Path=Ystr}" />
<Setter Property="Canvas.Left" Value="{Binding Path=Xstr}" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
I have used an observable collection PointList of Points(X,Y). I made the mistake at first of using integers for X and Y instead of strings. This was very difficult to debug since there was no error message when trying to bind the Canvas.Top to an integer. Is there a setting in Visual Studio to be able to catch this kind of error?
UPDATE
I have found that the binding works on an int property, but not with a public int field. Here is a Point class I created to test this out:
class Point
{
public int _X; //I know this is usually private, this is to demonstrate
public int _Y; //the issue with binding to a public field
public string Xstr
{
get { return _X.ToString(); }
}
public string Ystr
{
get { return _Y.ToString(); }
}
public int X
{
get { return _X; }
private set { _X = value; }
}
public int Y
{
get { return _Y; }
private set { _Y = value; }
}
public Point(int x, int y)
{
_X = x;
_Y = y;
}
}
If I bind to the int property X or string property Xstr it works fine. If I try to use the public field _X then it seems the binding cannot find the class member (even though it is public). So when a binding fails, the behavior is not the same as an exception in your code. An error like the following shows up in the output window, but the application does not stop:
System.Windows.Data Error: 40 : BindingExpression path error: '_X' property not found on 'object' ''Point' (HashCode=7877106)'. BindingExpression:Path=_X; DataItem='Point' (HashCode=7877106); target element is 'ContentPresenter' (Name=''); target property is 'Left' (type 'Double')