如何将DataContext添加到usercontrol的xaml?

时间:2013-04-20 13:15:11

标签: windows-phone-7 xaml

我尝试在我的usercontrol中设置:

d:DataContext="{d:DesignData ListItemDemoData.xaml}"

但是,Visual Studio声明找不到ListItemDemoData,而不是ListItemDemoData.xaml,只有ListItemDemoData

奇怪,我做错了吗?

1 个答案:

答案 0 :(得分:1)

您可以在后面的代码上执行此操作。 我有一个用于显示大图像的usercontrol。我的控件名称是ImageViewer。现在我必须绑定图像源。所以,我创建了一个依赖属性,如

    public static readonly DependencyProperty ValueProperty =
       DependencyProperty.Register("ImageSourceValue", typeof(string), typeof(ImageViewer),
       new PropertyMetadata(ValueChanged));

    public string ImageSourceValue
    {
        get { return (string)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }

    /// <summary>
    /// Called when the value of ImageSourceValue is changed or set.
    /// </summary>
    public static void ValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
    {
        // Get out of a static and into the instance ASAP.
        ImageViewer control = (ImageViewer)sender;
        control.ValueChanged();

    }

    private void ValueChanged()
    {
        //The value of ImageSourceValue is set at the time calling user control from your page.
        this.ImageSource = ImageSourceValue;

        this.DataContext = this;
    }

    public string ImageSource { get; set; }

我在将值绑定到图像控件时使用了转换器,该控件将字符串图像路径转换为bitmapimage对象。字符串ImageSource可以更改为BitmapImage类型。并且可以在将ImageSourceValue的值分配给ImageSource时完成转换。