为什么我的UserControl绑定不起作用?

时间:2011-08-13 14:45:28

标签: c# wpf xaml data-binding

我认为这样做很简单但似乎我必须错过一些明显的盲目。

问题是我将值传递给 UserControl (BoxPanel),但不会显示值。显示蓝色框没有文字。

MainWindow.xaml

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:l="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <l:BoxPanel Number="1" Text="Hi" />
    </Grid>
</Window>

BoxPanel.xaml

<UserControl x:Class="WpfApplication1.BoxPanel"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         Height="50" Width="90">
<Border Background="Blue">
    <StackPanel>
        <TextBlock FontSize="20" HorizontalAlignment="Center" 
            Text="{Binding Number}" />
        <Label FontSize="10" HorizontalAlignment="Center" Foreground="White" 
            Content="{Binding Text}" />
    </StackPanel>
</Border>

BoxPanel.xaml.xs

public partial class BoxPanel : UserControl
{
    public static readonly DependencyProperty NumberProperty = 
        DependencyProperty.Register("Number", typeof(decimal), typeof(BoxPanel));
    public static readonly DependencyProperty TextProperty = 
        DependencyProperty.Register("Text", typeof(string), typeof(BoxPanel));

    public BoxPanel()
    {
        InitializeComponent();
    }

    public decimal Number
    {
        get { return (decimal)GetValue(NumberProperty); }
        set { SetValue(NumberProperty, value); }
    }

    public string Text
    {
        get { return (string)base.GetValue(TextProperty); }
        set { base.SetValue(TextProperty, value); }
    }
}

1 个答案:

答案 0 :(得分:0)

默认情况下,绑定路径以DataContext为根。但是您希望绑定到UserControl上定义的属性。所以你必须以某种方式重定向它们。我通常只是ElementName

<UserControl x:Class="WpfApplication1.BoxPanel"
         x:Name="BoxPanelRoot"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         Height="50" Width="90">
<Border Background="Blue">
    <StackPanel>
        <TextBlock Text="{Binding Number, ElementName=BoxPanelRoot}" />
        <Label Content="{Binding Text, ElementName=BoxPanelRoot}" />
    </StackPanel>
</Border>

起初看起来有点奇怪,并且有点像这样重定向绑定有点烦人,但它比使用UserControl中的DataContext的其他方法更受欢迎。如果通过将DataContext设置为UserControl的根来阻止DataContext,则实际上已阻止了将数据传递到UserControl的最佳方法。

经验法则,在UserControl中绑定时,除了显式绑定传递给 UserControl的数据之外,保留DataContext。