I am new to WPF / XAML. I would like to receive an error message if I bind to the wrong data type in XAML. XAML seems to want all the bindings to be through strings, but there are no error messages if you use int or double by mistake.
I found this XAML code here :
<ItemsControl ItemsSource="{Binding Path=PointList}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Canvas /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <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 used an observable collection of PointList points (X, Y). At first I made a mistake 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 Canvas.Top to an integer. Is there a parameter in Visual Studio to catch such an error?
UPDATE
I found that the binding works on the int property, but not with the int field open. Here is the Point class I created to test this:
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 an int X property or an Xstr string property, it works fine. If I try to use the public field _X, it seems that the binding cannot find the member of the class (even if it is public). Therefore, when the binding does not work, the behavior does not match the behavior in the code. An error similar to the following appears 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')
source share