Data binding 为什么Lightswitch自定义控件忽略数据上下文并需要完整路径?
我一直在尝试Lightswitch并尝试添加自定义控件,但所有示例和测试都表明数据绑定有问题 例如,我有一个颜色表,其成员名为:Data binding 为什么Lightswitch自定义控件忽略数据上下文并需要完整路径?,data-binding,visual-studio-lightswitch,Data Binding,Visual Studio Lightswitch,我一直在尝试Lightswitch并尝试添加自定义控件,但所有示例和测试都表明数据绑定有问题 例如,我有一个颜色表,其成员名为: string ColorName; // Name of colour string ColorHex; // #Html Color string 我有一个简单的自定义控件,它将其中一种颜色显示为一个带有名称的小样例 <UserControl xmlns:sdk="http://schemas.microsoft.com/winfx/
string ColorName; // Name of colour
string ColorHex; // #Html Color string
我有一个简单的自定义控件,它将其中一种颜色显示为一个带有名称的小样例
<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>
作为测试,我向屏幕添加了SelectedColor属性,然后添加了自定义控件,并将其数据上下文设置为SelectedColor
然后,您可能希望控件中的绑定只需要是“ColorName”
和“ColorHex”
,但是绑定的实际数据上下文似乎是继承者权限(屏幕上方)的更高的内容,您需要有一个类似于“Screen”的路径。而不是SelectedColor.ColorHex“
。分配给自定义控件的数据上下文值似乎被完全忽略
我做错了什么?在自定义控件中具有完整绑定路径是没有意义的,因为它们不应该知道数据来自何处(仅在上下文中具有特定成员)。Lightswitch out的许多绑定示例似乎不仅具有误导性,但是鼓励使用完全不可移植的方式绑定自定义控件 在深入研究之后,我发现如果将自定义控件的数据上下文设置为屏幕中的实体,那么DataContext不仅会接收
screen
属性(每个人似乎都使用该属性进行绑定),还会接收值
属性(这是屏幕选择的特定项目)
上述示例的正确绑定为:
<Rectangle Fill="{Binding Path=Value.ColorHex, Converter={StaticResource ColorToSolidColorBrushConverter}}" Margin="3" />
<TextBox Text="{Binding Path=Value.ColorName}" Grid.Column="1" />
简单(一旦你知道怎么做)