将数据绑定到由DataTemplate托管的UserControl

时间:2013-01-02 09:53:34

标签: wpf winrt-xaml

我有一个用户控件,它暴露了一个很长的属性。我想实例化此控件并绑定到数据模板中的公开属性。

我在资源文件中看到xaml错误。含糊不清的“必须将面板的衍生物作为根元素”。当我在调试器中运行它时,我看到TeamIdx的值为-1且未设置。

<DataTemplate x:Key="TeamScheduleTemplate">
    <Grid HorizontalAlignment="Left" Width="400" Height="600">
        <Team:ScheduleControl TeamIdx="{Binding Idx}" />
    </Grid>
</DataTemplate>



public sealed partial class ScheduleControl : UserControl
{
    public static readonly DependencyProperty TeamIdxProperty =
        DependencyProperty.Register(
        "TeamIdx",
        typeof(long),
        typeof(ScheduleControl),
        new PropertyMetadata((long)-1));

    public long TeamIdx
    {
        get { return (long)GetValue(TeamIdxProperty); }
        set { SetValue(TeamIdxProperty, value); }
    }

    public ScheduleControl()
    {
        this.InitializeComponent();

        var team = TeamLookup.GetTeam(TeamIdx);
    }
}

1 个答案:

答案 0 :(得分:0)

编辑:事实证明,直到构造控件之后才会发生绑定。回想起来,这完全有道理。我使用的解决方案如下:

public sealed partial class ScheduleControl : UserControl
{
    public static readonly DependencyProperty TeamIdxProperty =
        DependencyProperty.Register(
        "TeamIdx",
        typeof(long),
        typeof(ScheduleControl),
        new PropertyMetadata(
            (long)-1,
            OnTeamIdxChanged));

    public long TeamIdx
    {
        get { return (long)GetValue(TeamIdxProperty); }
        set { SetValue(TeamIdxProperty, value); }
    }

    private static void OnTeamIdxChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        var target = (ScheduleControl)sender;
            target.OnTeamIdxChanged((long)e.NewValue);
    }

    private void OnTeamIdxChanged(long id)
    {
        var model = FindModel(id);
        this.DataContext = model;
    }


    public ScheduleControl()
    {
        this.InitializeComponent();
    }
}