Windows 10 開發日記(五)-- 當Binding遇到異步 -- 解決方案


前文再續,上一章提出了問題,本章提出了三種解決方案:

?

解決方案一:手動進行異步轉換,核心思想:將binding做的事情放入CodeBehind

?

FilterItemControl.XAML:

    <Grid><Image x:Name="FilterImage" Stretch="UniformToFill"/><Grid VerticalAlignment="Bottom" Height="20"><TextBlock x:Name="FilterName" TextWrapping="Wrap" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White"/></Grid><Border x:Name="border" BorderBrush="White" BorderThickness="1" d:LayoutOverrides="LeftPosition, RightPosition, TopPosition, BottomPosition" Margin="1" Visibility="Collapsed"/></Grid>

  

FilterItemControl.cs

 /// <summary>/// 設置數據源/// </summary>/// <param name="filter"></param>public async void SetSource(Filter filter){if (filter != null){_filter = filter;// 使用WriteableBitmap有一個不好的點:必須要知道圖片的大小WriteableBitmap result = new WriteableBitmap(768, 1280);var wbData = await MyFilterSDK.ProcessFilterAsync(filter);if(wbData != null){using (var bmpStream = result.PixelBuffer.AsStream()){bmpStream.Seek(0, SeekOrigin.Begin);bmpStream.Write(wbData, 0, (int)bmpStream.Length);}FilterImage.Source = result;}FilterName.Text = filter.FilterName;}}

為其設置數據源, FilterItemsControl.cs

/// <summary>/// 數據源發生變化/// </summary>/// <param name="filters">濾鏡列表</param>private void OnItemsSourceChanged(List<Filter> filters){if(filters != null){Container.Children.Clear();foreach(var filter in filters){FilterItemControl itemcontrol = new FilterItemControl();itemcontrol.Width = ITEMWIDTH;itemcontrol.Height = ITEMHEIGHT;// 將binding中做的事情放到代碼中!itemcontrol.SetSource(filter);
itemcontrol.ItemSelected += Itemcontrol_ItemSelected;itemcontrol.ItemDoubleClicked += Itemcontrol_ItemDoubleClicked;Container.Children.Add(itemcontrol);}}}

  優點:方便簡單

? ? ? 缺點:XAML必須寫死,沒有擴展性,如果同樣的數據變換一種顯示方式,需要重寫一個控件。

?

解決方案二:使用異步屬性,核心思想,使用Binding和異步加載

?

FilterItemControl.xaml

    <Grid><Image x:Name="FilterImage" Stretch="UniformToFill" Source="{Binding WBAsyncProperty.AsyncValue, Converter={StaticResource imagConverter}}"/><Grid VerticalAlignment="Bottom" Height="20"><TextBlock x:Name="FilterName" TextWrapping="Wrap" Text="{Binding FilterName}" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White"/></Grid><Border x:Name="border" BorderBrush="White" BorderThickness="1" d:LayoutOverrides="LeftPosition, RightPosition, TopPosition, BottomPosition" Margin="1" Visibility="Collapsed"/></Grid>

FilterItemControl.cs不需要額外的東西,但是Model層的數據源需要增加一個異步屬性用于被View層綁定

Filter.cs

        private AsyncProperty<byte[]> _wbAsyncProperty; // 異步屬性public AsyncProperty<byte[]> WBAsyncProperty{get{return _wbAsyncProperty;}set{SetProperty(ref _wbAsyncProperty, value);}} 

     // 初始化public Filter(){WBAsyncProperty = new AsyncProperty<byte[]>(async () =>{var result = await MyFilterSDK.ProcessFilterAsync(this);return result;});}

  

由于返回值是byte[]類型,所以我們在binding時,必須要進行一次轉換,將其轉換為WriteableBitmap:BytesToImageConverter.cs

public class BytesToImageConverter : IValueConverter{public object Convert(object value, Type targetType, object parameter, string language){// 使用WriteableBitmap有一個不好的點:必須要知道圖片的大小WriteableBitmap result = new WriteableBitmap(768, 1280);var filterData = value as byte[];if (filterData != null){#region  WriteableBitmap方案using (var bmpStream = result.PixelBuffer.AsStream()){bmpStream.Seek(0, SeekOrigin.Begin);bmpStream.Write(filterData, 0, (int)bmpStream.Length);return result;}#endregion}elsereturn null;}public object ConvertBack(object value, Type targetType, object parameter, string language){throw new NotImplementedException();}}

  關于如何實現AsyncProperty和其工作原理在這里不做深究,在這里總結一下這個方案的優缺點:

優點:使用Binding,UI上不會卡頓,圖片獲取完之后會顯示在UI上

缺點: 1. 控件重用性不高

? ? ? ? 2. SDK必須與UI無關,這也是為什么返回byte[],而不是直接返回WrieableBitmap的原因,與AsyncProperty的實現技術有關

? ? ? ? 3. 因為原因2,必須實現轉換器

?

解決方案三:使用DataTemplate,核心思想:將DataTemplate轉換放到CodeBehind

?FilterItemControl.XAML需要改變,這里只需要一個ContentPresenter接收內容

   <Grid>  
<ContentPresenter x:Name="Presenter"/><Border x:Name="border" BorderBrush="White" BorderThickness="1" d:LayoutOverrides="LeftPosition, RightPosition, TopPosition, BottomPosition" Margin="1" Visibility="Collapsed"/></Grid>

FilterItemControl.cs需要增加一個ContentTemplate,用于獲取應用在這個控件上的模板,并且根據模板把UI顯示出來:

   public DataTemplate ContentDataTemplate{get { return (DataTemplate)GetValue(ContentDataTemplateProperty); }set { SetValue(ContentDataTemplateProperty, value); }}public static readonly DependencyProperty ContentDataTemplateProperty =DependencyProperty.Register("ContentDataTemplate", typeof(DataTemplate), typeof(FilterItemControl3), new PropertyMetadata(null,OnContentDataTemplateChanged));private static void OnContentDataTemplateChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args){FilterItemControl3 owner = sender as FilterItemControl3;owner.OnContentDataTemplateChanged(args.NewValue as DataTemplate);}private async void OnContentDataTemplateChanged(DataTemplate newDataTemplate){UIElement rootElement = newDataTemplate.LoadContent() as UIElement;if(rootElement != null){Image img = VisualTreeExtensions.FindFirstElementInVisualTree<Image>(rootElement);if (img != null){#region 使用SDK 處理WriteableBitmap result = new WriteableBitmap(768, 1280);var wbData = await MyFilterSDK.ProcessFilterAsync(this.DataContext as Filter);if (wbData != null){using (var bmpStream = result.PixelBuffer.AsStream()){bmpStream.Seek(0, SeekOrigin.Begin);bmpStream.Write(wbData, 0, (int)bmpStream.Length);}img.Source = result;}#endregion// 改變了圖片之后,需要將其加入到可視化中以顯示,如果不加這一步你可以想象會出現什么情況Presenter.Content = rootElement;}}}

同樣的,需要修改FilterItemsControl.cs,增加一個ItemDataTemplate傳遞給FilterItemControl:

        /// <summary>/// 子項的模板/// </summary>public DataTemplate ItemDataTemplate{get { return (DataTemplate)GetValue(ItemDataTemplateProperty); }set { SetValue(ItemDataTemplateProperty, value); }}public static readonly DependencyProperty ItemDataTemplateProperty =DependencyProperty.Register("ItemDataTemplate", typeof(DataTemplate), typeof(FilterItemsControl3), new PropertyMetadata(0));/// <summary>/// 數據源發生變化/// </summary>/// <param name="filters">濾鏡列表</param>private void OnItemsSourceChanged(List<Filter> filters){if (filters != null){Container.Children.Clear();foreach (var filter in filters){FilterItemControl3 itemcontrol = new FilterItemControl3();//itemcontrol.Width = ITEMWIDTH; // 不要了,在DataTemplate中指定//itemcontrol.Height = ITEMHEIGHT;//1. 設置DataContextitemcontrol.DataContext = filter;//2. 設置模板itemcontrol.ContentDataTemplate = ItemDataTemplate;itemcontrol.ItemSelected += Itemcontrol_ItemSelected;itemcontrol.ItemDoubleClicked += Itemcontrol_ItemDoubleClicked;Container.Children.Add(itemcontrol);}}}

那么我們只需要在使用這個控件的地方編寫一個ItemDataTemplate就可以了:

<local:FilterItemsControl3 x:Name="FilterItemsUserControl" Opacity="0" RenderTransformOrigin="0.5,0.5" Margin="0"><local:FilterItemsControl3.RenderTransform><CompositeTransform TranslateY="100"/></local:FilterItemsControl3.RenderTransform><local:FilterItemsControl3.ItemDataTemplate><DataTemplate><Grid Width="80" Height="80"><Image x:Name="SourceImage"/><Grid Height="20" VerticalAlignment="Top" Background="#7F000000"><TextBlock x:Name="textBlock" TextWrapping="Wrap" Text="{Binding FilterName}" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White"/></Grid></Grid></DataTemplate></local:FilterItemsControl3.ItemDataTemplate></local:FilterItemsControl3>

 第三種方案是我想表達的,但是我們看出來,它也并不是最優的,需要在代碼中取出DataTemplate中的可視元素,然后將SDK處理過的圖片放到目標Image控件的Source中去,但是他的優點也是有的: 1. UI的可擴展性

? ? ? ? ? ? ? ? ? ? ? ? ? ? ?2. 與異步無關的屬性可以通過Binding展示

可以說,方案三模擬了DataTemplate如何應用在一個控件上的,這也是我想從這個例子中總結的東西:

1. DataTemplate的作用

2. 控件在應用了DataTemplate之后發生了什么?

3. 通過DataTemplate.LoadContent(), 獲取控件,并且修改控件,如果不使用Presenter.Content = rootElement, 為什么沒有反應?

?

總結:

1. 首先DataTemplate的MSDN的解釋非常清楚,就是將“數據"轉換為可見的元素,這也是為什么我們選擇DataTemplate來展示Filter的原因。

2. 控件在應用了DataTemplate之后會發生什么?因為微軟的封閉,我們看不到,但是可以猜到,它的實現類似于我們方案三的實現:取得DataTemplate中的元素,并且將其加載到可視化樹中顯示。我們在XAML中寫的DataTemplate類似于一個類的聲明,當某個控件需要這個DataTemplate時,會new 一個實例,然后目標控件,并且替換它之前的可視化樹。

3. 第三個問題的答案基于第二個問題:通過DataTemplate.LoadContent()獲得的UIElement每次都是不一樣的,就是說調用該方法就類似與調用 new DataTemplate(),一樣,只是一次實例化,此時的元素并沒有加載到可視化樹中(可以通過GetHashCode()對比),所以,無論做什么修改,你都看不出結果。所以必須要有Presenter.Content = rootElement這關鍵的一步。

?

Demo已經寫好,VS2015工程,WU框架,PC運行。

MyFilterDemo.rar

轉載于:https://www.cnblogs.com/DinoWu/p/4549770.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/258812.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/258812.shtml
英文地址,請注明出處:http://en.pswp.cn/news/258812.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

fseek

int fseek( FILE *stream, long offset, int origin );第一個參數stream為文件指針第二個參數offset為偏移量&#xff0c;正數表示正向偏移&#xff0c;負數表示負向偏移第三個參數origin設定從文件的哪里開始偏移,可能取值為&#xff1a;SEEK_CUR、 SEEK_END 或 SEEK_SETSEEK_…

static_cast, dynamic_cast, const_cast探討【轉】

首先回顧一下C類型轉換&#xff1a; C類型轉換分為&#xff1a;隱式類型轉換和顯式類型轉換 第1部分. 隱式類型轉換又稱為“標準轉換”&#xff0c;包括以下幾種情況&#xff1a;1) 算術轉換(Arithmetic conversion) : 在混合類型的算術表達式中, 最寬的數據類型成為目標轉換類…

RANSAC算法注記

今天學習了一下RANSAC隨機樣本一致性算法&#xff0c;其在圖像融合、特征點匹配方面有很強大的應用。網上已經有很多人寫了關于這方面的文檔&#xff0c;就不再造輪子了。特此羅列出來&#xff0c;以供后續參考。 我的數學之美&#xff08;一&#xff09;——RANSAC算法詳解 …

python字典格式_python – 格式self,這是一個字典

在這種情況下如何使格式(自我)工作&#xff1f;class Commit:number Nonesha Nonemessage Noneidentity Nonedef __init__(self, raw, number):r raw.commits[number]self.number numberself.sha r[sha]self.message r[message]self.identity raw.identities[r[identi…

委托的BeginInvoke和EndInvoke

剛剛搞明白了C#的異步調用&#xff0c;寫下來&#xff0c;方便后續調用。 異步主要是解決UI假死的問題&#xff0c;而開辟出一個新的線程&#xff0c;處理大數據。 1.既然是委托的調用&#xff0c;那么先定義個委托&#xff1a; public delegate bool CheckUpdateFile(); 2.定義…

PMP 第七章 項目成本管理

估算成本 制定預算 控制成本 1.成本管理計劃的內容和目的是什么? 包括對成本進行估算 預算和控制的各過程&#xff0c;從而確保項目在批準的預算內完工。 2.直接成本、間接成本、可變成本、固定成本、質量成本的內容分別是什么?成本估算的工具有哪些? 成本估算工具 1…

您的請求參數與訂單信息不一致_[淘客訂單檢測]淘寶客訂單檢測接口,淘客訂單查詢API...

功能1.輸入交易的訂單編號&#xff0c;即可查詢該訂單是否為淘寶客訂單。有意向請聯系衛星weixiaot168。2.查詢結果 0:不是淘寶客訂單&#xff1b;1:是。3.根據淘寶官方的后臺數據&#xff0c;進行檢測&#xff0c;數據真實且有效。4.有效防止傭金損失&#xff0c;降低商家補單…

DebugView輸出調試信息

在寫windows程序時&#xff0c;需要輸出一些調試信息&#xff0c;這里介紹一種極其方便的方法。即使用OutputDebugString 在Debug模式下輸出調試信息&#xff0c;在Release模式下不輸出。 我們可以在VS的集成平臺上輸出調試信息&#xff0c;也可以使用DebugView來查看調試信息…

Linux上實現ssh免密碼登陸遠程服務器

0.說明平常使用ssh登陸遠程服務器時&#xff0c;都需要使用輸入密碼&#xff0c;希望可以實現通過密鑰登陸而免除輸入密碼&#xff0c;從而可以為以后實現批量自動部署主機做好準備。環境如下&#xff1a;IP地址操作系統服務器端10.0.0.128/24CentOS 6.5 x86客戶端10.0.0.129/2…

【強連通分量+概率】Bzoj2438 殺人游戲

Description 一位冷血的殺手潛入 Na-wiat&#xff0c;并假裝成平民。警察希望能在 N 個人里面&#xff0c;查出誰是殺手。 警察能夠對每一個人進行查證&#xff0c;假如查證的對象是平民&#xff0c;他會告訴警察&#xff0c;他認識的人&#xff0c; 誰是殺手&#xff0c; 誰是…

serialversionuid的作用_為什么阿里Java規約要求謹慎修改serialVersionUID字段

serialVersionUID簡要介紹serialVersionUID是在Java序列化、反序列化對象時起作用的一個字段。Java的序列化機制是通過判斷類的serialVersionUID來驗證版本一致性的。在進行反序列化時&#xff0c;JVM會把傳來的字節流中的serialVersionUID與本地相應實體類的serialVersionUID進…

fatal error LNK1169: 找到一個或多個多重定義的符號 的解決方案

昨天&#xff0c;嘗試一個項目&#xff0c;遇到了如下的問題。先來還原一下&#xff1a; 頭文件test.h #pragma once #include <Eigen/Core> #include <iostream>using namespace Eigen; using namespace std;class point2 { public: point2(int x1,int y1):x(x…

常用工具說明--搭建基于rietveld的CodeReview平臺(未測試)

為什么要codereview . 整個團隊的編碼風格是統一的。 . 有高手能對自己的代碼指點一二&#xff0c;從而提高編碼水平。 . 減少低級錯誤的出現 . 約束自己寫高質量的代碼&#xff0c;因為是要給人看的。 我們對codereview的需求 . 很輕松可以發布自己寫的代碼。 . 很輕松的可以與…

輸入的優化

讀入整型時&#xff0c;輸入優化可以節省不少時間 1 typedef type long long 2 // 這里以long long為例 3 type read() { 4 type x0; int f1; 5 char chgetchar(); 6 while(ch<0||ch>9) {if(ch-) f-1; chgetchar();} 7 while(ch>0&&ch<9) …

python股票分析系統_熬了一晚上,小白用Python寫了一個股票提醒系統

碼農小馬七夕節去相親了&#xff0c;見了一個不錯的姑娘&#xff0c;長的非常甜美&#xff01;聊著聊著很投緣&#xff01;通過介紹人了解到&#xff0c;對方也很滿意&#xff5e;&#xff5e;想著自己單身多年的生活就要結束啦&#xff0c;心里滿是歡喜&#xff0c;美美噠&…

有關eigen庫的一些基本使用方法

目錄 介紹安裝Demo矩陣、向量初始化C數組和矩陣轉換矩陣基礎操作點積和叉積轉置、伴隨、行列式、逆矩陣計算特征值和特征向量解線性方程最小二乘求解稀疏矩陣介紹 Eigen是一個輕量級的矩陣庫,除了稀疏矩陣不成熟&#xff08;3.1有較大改進&#xff09;以外,其他的矩陣和向量操作…

匯編程序:將字符串中所有大寫字符轉為小寫

【任務】 編寫程序&#xff0c;將數據區中定義的以0作為結束符的一個字符串中所有的大寫字符&#xff0c;全部轉換為小寫。 【參考解答】 assume cs:cseg, ds:dseg, ss:sseg sseg segment stackdw 100h dup (?) sseg ends dseg segmentdb YanTai123University, 0 d…

從零開始編寫自己的C#框架(1)——前言

記得十五年前自學編程時&#xff0c;拿著C語言厚厚的書&#xff0c;想要上機都不知道要用什么編譯器來執行書中的例子。十二年前在大學自學ASP時&#xff0c;由于身邊沒有一位同學和朋友學習這種語言&#xff0c;也只能整天混在圖收館里拼命的啃書。而再后來也差不多&#xff0…

Bash內置命令

Bash有很多內置命令&#xff0c;因為這些命令是內置的&#xff0c;因此bash不需要在磁盤上為它們定位&#xff0c;執行速度更快。 1&#xff09;列出所有內置命令列表$enable 2&#xff09;關閉內置命令test$enable -n test 3&#xff09;打開內置命令test$enable test 4&…

postman調用webservice接口_接口對前后端和測試的意義

1.什么是接口&#xff1f;接口測試主要用于外部系統與系統之間以及內部各個子系統之間的交互點&#xff0c;定義特定的交互點&#xff0c;然后通過這些交互點來&#xff0c;通過一些特殊的規則也就是協議&#xff0c;來進行數據之間的交互。2.接口都有哪些類型&#xff1f;接口…