WPF绑定到DataTemplate中UserControl的DependencyProperty不起作用

时间:2013-04-30 06:18:03

标签: wpf binding user-controls datatemplate dependency-properties

我有一个带DP的自定义userControl,并且存在这样的问题:只有在我使用datatemplates外部的控件时,对这些属性的绑定才有效。

在Datatemplates之外,用户控制非常好。

XAML测试DataTemplate中的UserControl

        <GroupBox Header="DataTemplate" Padding="5">

            <ItemsControl ItemsSource="{Binding Dummies}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate DataType="local:Dummy">
                        <StackPanel Orientation="Horizontal" Margin="2">

                            <common:QuarterPicker SelectedFirstDay="{Binding Gueltigkeit}" Margin="5,0" />

                            <!--control the value of the item-->
                            <TextBlock Text="Gueltigkeit: "/>
                            <TextBlock Text="{Binding Gueltigkeit}"/>

                        </StackPanel>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>

            </ItemsControl>

        </GroupBox>

MainWindow代码隐藏和ViewModel

public partial class QuarterPickerTest : UserControl
{
    public QuarterPickerTest()
    {
        InitializeComponent();

        this.DataContext = new ViewModel();
    }
}

public class ViewModel
{
    public ViewModel()
    {
        this.Dummy = new Dummy { Gueltigkeit = DateTime.Today };

        this.Dummies = new List<Dummy>
            {
                new Dummy {Gueltigkeit = DateTime.Today},
                new Dummy {Gueltigkeit = DateTime.Today.AddMonths(6)},
                new Dummy {Gueltigkeit = DateTime.Today.AddDays(-6)},
            };
    }

    public Dummy Dummy { get; set; }

    public List<Dummy> Dummies { get; set; }
}

以下是我的UserControl背后的代码

#region SelectedFirstDay

    public DateTime SelectedFirstDay
    {
        get { return (DateTime)GetValue(SelectedFirstDayProperty); }
        set { SetValue(SelectedFirstDayProperty, value); }
    }

    public static readonly DependencyProperty SelectedFirstDayProperty
        = DependencyProperty.Register("SelectedFirstDay", typeof (DateTime), typeof (QuarterPicker),
                                      new FrameworkPropertyMetadata(DateTime.Today, SelectedFirstDayPropertyChangedCallback) { BindsTwoWayByDefault = true });

    private static void SelectedFirstDayPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
    {
        var quarterPicker = dependencyObject as QuarterPicker;
        var date = (DateTime)args.NewValue;
        var quarter = GetQuarter(date);

        quarterPicker.UpdateProperties(date.Year, quarter);

        if (date.Year == quarterPicker.LeftInfiniteYear && quarter == quarterPicker.LeftInfiniteQuarter)
            quarterPicker.ShowPopupButtonLeftInfinite();
    }

    #endregion

感谢您的任何建议!

0 个答案:

没有答案