欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

wpf/WP/C#/Sliverlight 自定义控件,绑定依赖属性

程序员文章站 2022-03-04 11:49:56
...

自定义控件,绑定依赖属性

有时候需要绑定一个自定义的依赖属性,比如你有个Image控件,如果在默认的属性Source赋值设置某个url如:http://f.hiphotos.baidu.com/image/h%3D360/sign=f7030d1d1a178a82d13c79a6c602737f/6c224f4a20a446237cd252b39c22720e0df3d7c3.jpg

的时候不见得能显示这个图片,因为百度有防盗链措施,其实就是判断了请求的来源是否为百度自己的网站服务器,解决方法就是http请求的header 里的"Referer"设置为"http://www.baidu.com"

//也可这样去请求
// HttpWebRequest re = (HttpWebRequest)WebRequest.Create("http://f.hiphotos.baidu.com/image/h%3D360/sign=f7030d1d1a178a82d13c79a6c602737f/6c224f4a20a446237cd252b39c22720e0df3d7c3.jpg");
// re.Headers["Referer"]= "http://www.baidu.com";

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
using Windows.Storage.Streams;
using System.Runtime.InteropServices.WindowsRuntime;

namespace wgscd_test
{
public class ImageEx:UserControl
{
public ImageEx()
{
img = new Image();
Content = img;

    }
    Image img;
    BitmapImage bmp;
    //注册依赖属性
    public static DependencyProperty UrlProperty = DependencyProperty.Register("Url",
                                       typeof(string),
                                       typeof(ImageEx),
                                       new PropertyMetadata("默认属性值", OnUrlPropertyChanged));

    //依赖属性对应的控件属性
    public string Url
    {
        get { return (string)GetValue(UrlProperty); }
        set { SetValue(UrlProperty, value); }
    }

    //依赖属性回掉函数(static)
    private static void OnUrlPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        //这里MySilverButton是控件类名
        var mySilverButton = d as ImageEx;
        if (mySilverButton != null)
        {
            mySilverButton.PropertyChangedMethodFun(e);
        }
    }

    bool loaded = false;
    //属性变化回掉(通过静态函数调用,也可以在静态函数里写)
    private async void PropertyChangedMethodFun(DependencyPropertyChangedEventArgs e)
    {
        // var bgTextBlock = GetTemplateChild("ButtonCaption") as TextBlock;
        //  if (bgTextBlock != null) bgTextBlock.Text = e.NewValue as string;
        if (e.NewValue != e.OldValue && ""+e.NewValue!="") {

            if (loaded) return;
            loaded = true;
          //  await System.Threading.Tasks.Task.Delay(5000);
            try {
                HttpClient client = new HttpClient();
                var bytes = await client.GetByteArrayAsync("" + e.NewValue);
                IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(bytes, 0, bytes.Length);
                //Ibuffer转IrandomAccessStream
                InMemoryRandomAccessStream inStream = new InMemoryRandomAccessStream();
                DataWriter datawriter = new DataWriter(inStream.GetOutputStreamAt(0));
                datawriter.WriteBuffer(buffer, 0, buffer.Length);
                await datawriter.StoreAsync();
                // bmp = new BitmapImage(new Uri(""+e.NewValue ,UriKind.Absolute ));
                // img.Source = bmp;
                bmp = new BitmapImage();
                bmp.SetSourceAsync(inStream);
                img.Source = bmp;
            }
            catch { }
        }

    }


}

}

这个自定义控件就可在设置 URL的时候自动去请求这个图片了!

例子里的HTTP请求可以改为你实际情况适合的方式 如 webclient ,HttpWebRequest 这种方式!

调用直接设置Url就是
如: 《UI:ImageEx Url ="{Binding url}" Width="222" Height="380"
注意 Url ="{Binding url} 就是绑定的图片地址数据

        ObservableCollection ObservableObj = new ObservableCollection<object>();
        ObservableObj.Add(new { url = "http://img1.mm131.com/pic/1918/1.jpg", Name = "帅1", Sex = "男", Age = 20 });
        ObservableObj.Add(new { url = "http://img1.mm131.com/pic/1918/2.jpg", Name = "帅2", Sex = "女", Age = 60 });
        ObservableObj.Add(new { url = "http://img1.mm131.com/pic/1918/3.jpg", Name = "帅3", Sex = "女", Age = 50 });
        ObservableObj.Add(new { url = "http://img1.mm131.com/pic/1918/4.jpg", Name = "帅4", Sex = "女", Age = 40 });
        ObservableObj.Add(new { url = "http://img1.mm131.com/pic/1918/5.jpg", Name = "帅5", Sex = "男", Age = 20 });
        list2.ItemsSource = ObservableObj;

转载于:https://www.cnblogs.com/wgscd/articles/5092016.html