Reputation: 93571
I have been experimenting with Lightswitch and trying to add custom controls, but all the examples and my test indicate something is wrong with the data binding.
For example, I have a colour table with members called:
string ColorName; // Name of colour
string ColorHex; // #Html Color string
I have a simple custom control that displays one of these colours as a small swatch with its name.
<UserControl
xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
x:Class="LightSwitch.UserControls.HtmlColorControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Vero.LightSwitch.UserControls"
mc:Ignorable="d"
d:DesignHeight="30" d:DesignWidth="400">
<UserControl.Resources>
<local:ColorToSolidColorBrushValueConverter x:Key="ColorToSolidColorBrushConverter"/>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="#FF28DFE8" MinWidth="100">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="30"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Rectangle Fill="{Binding Path=Screen.SelectedColor.ColorHex, Converter={StaticResource ColorToSolidColorBrushConverter}}" Margin="3" />
<TextBox Text="{Binding Path=Screen.SelectedColor.ColorName}" Grid.Column="1" />
</Grid>
</UserControl>
As a test I added a SelectedColor property to the Screen, then added the custom control with its Data Context set to SelectedColor.
You would expect then that the bindings in the control would only need to be "ColorName"
and "ColorHex"
, but the actual data context for the bindings appears to be something higher up the heirarchy (above the Screen) and you need to have a path like "Screen.SelectedColor.ColorHex"
instead. The Data Context value assigned to the custom control seems to be completely ignored.
What am I doing wrong? It makes no sense to have full binding paths inside a custom control as they should not know where the data is coming from (only that is has specific members on the context).
Upvotes: 0
Views: 856
Reputation: 93571
It appears that lots of the binding examples for Lightswitch out there are not only misleading, but encourage a completely non-portable way of binding Custom Controls.
After much diving under the covers, I found that if you set the Data Context of a custom control to an entity within the screen, then the DataContext not only receives a Screen
property (which everyone seems to use for their binding), but it also receives a Value
property (which is the specific item chosen by the screen).
The correct bindings for the above example are:
<Rectangle Fill="{Binding Path=Value.ColorHex, Converter={StaticResource ColorToSolidColorBrushConverter}}" Margin="3" />
<TextBox Text="{Binding Path=Value.ColorName}" Grid.Column="1" />
Simple (once you know how)!
Upvotes: 2