如何将动态字节数组绑定到WPF中的按钮背景

我正在尝试创建一个具有一组特定值的自定义控件。 它还有一些自定义事件。 我一直在尝试将我从数据库中获取的字节数组(blob)转换为我的自定义控件背景(按钮)。

 

我的自定义控件:

 [JsonProperty("consoleButton.id")] public int id { get; set; } [JsonProperty("consoleButton.parent_id")] public int? parent_id { get; set; } [JsonProperty("consoleButton.console_id")] public int console_id { get; set; } [JsonProperty("consoleButton.image_link")] public byte[] image_link { get; set; } public string website_link { get; set; } [JsonProperty("consoleButton.tag_name")] public string tag_name { get; set; } [JsonProperty("consoleButton.button_type")] public Miscellaneous.Enums.buttontype button_type { get; set; } public int x { get; set; } public int y { get; set; } //public string name { get; set; } public BitmapImage brush { get; set; } public ImageButton(int id, int? parent_id, int console_id, byte[] image_link, string website_link, string tag_name, Miscellaneous.Enums.buttontype button_type, int x, int y, double convertSize) { InitializeComponent(); this.id = id; //this.name = "btn" + id.ToString(); this.parent_id = parent_id; this.console_id = console_id; this.image_link = image_link; this.website_link = website_link; this.tag_name = tag_name; this.button_type = button_type; this.x = Convert.ToInt32(x * convertSize); this.y = Convert.ToInt32(y * convertSize); BitmapImage btm; using (MemoryStream ms = new MemoryStream(image_link)) { btm = new BitmapImage(); btm.BeginInit(); btm.StreamSource = ms; // Below code for caching is crucial. btm.CacheOption = BitmapCacheOption.OnLoad; btm.EndInit(); btm.Freeze(); } brush = btm; } 

我已经尝试了一些你可以看到的东西(添加了额外的代码),但似乎没有任何工作。

将UserControl的UI元素绑定到UserControl的属性时,您必须将控件实例设置为Binding的源对象。

一种方法是设置RelativeSource属性:

  

请注意,您不需要像brush属性那样额外的ImageSource(或BitmapImage)属性。 WPF提供内置类型转换,它会自动将byte[]转换为ImageSource


由于控件的属性不会触发更改通知,因此在调用InitializeComponent之前可能还需要设置它们的值:

 public ImageButton(...) { ... this.image_link = image_link; ... InitializeComponent(); } 

你可以告诉我绑定到错误的属性:Source =“{image image_link}当我认为它应该是Source =”{binding brush}

(代码btw的微小重组):

  BitmapImage btm = new BitmapImage(); using (MemoryStream ms = new MemoryStream(image_link)) { ms.Position = 0; btm.BeginInit(); btm.StreamSource = ms; btm.CacheOption = BitmapCacheOption.OnLoad; btm.EndInit(); } btm.Freeze(); brush = btm;