用户控件中的 Silverlight 嵌套绑定



我尝试绑定一个bindig示例:

设置.xaml

<labels:KeyValueLabel Key="User name:" Label="{Binding Name}" Margin="10"/>

KeyValueLabel.xaml

<UserControl x:Class="rodzic.Controls.Labels.KeyValueLabel"
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"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
d:DesignHeight="100" d:DesignWidth="480">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <TextBlock x:Name="KeyLabel" Text="{Binding Key}"/>
    <TextBlock x:Name="ValueLabel" Text="{Binding Label}"/>
</Grid>

KeyValueLabel.xaml.cs

public partial class KeyValueLabel : UserControl
{
    public string Key { get; set; }
    public static readonly DependencyProperty LabelProperty = DependencyProperty.Register(
        "Label",
        typeof(String),
        typeof(KeyValueLabel),
        new PropertyMetadata("default", new PropertyChangedCallback(LabelChanged))
    );
    static void LabelChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        //e is always being set to ""
    }
    public string Label
    {
        get { return (string)GetValue(LabelProperty); }
        set { SetValue(LabelProperty, value); }
    }
    public KeyValueLabel()
    {
        InitializeComponent();
    }
}
如果我在settings.xaml

中将值作为静态文本传递,它可以工作,但是来自settings.xaml的绑定数据既不用于键也不用于标签。

如何修复标签绑定?无论绑定多么嵌套,我都想让它工作。

似乎要创建自定义控件,而不是用户控件。 这是两件完全不同的事情。 使用自定义控件,可以创建依赖项属性,然后像绑定任何其他控件一样直接绑定到它们。

然后,在自定义控件中捕获它的设置并直接设置 TextBlock 的 Text 属性。 因此,您不需要双重绑定。

最新更新