日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

为什么这儿TemplateBinding不起作用了—研究WPF Binding(一)

發布時間:2025/7/14 49 豆豆
生活随笔 收集整理的這篇文章主要介紹了 为什么这儿TemplateBinding不起作用了—研究WPF Binding(一) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

工作中,寫自定義控件,遇到一個奇怪的問題。場景是這樣的:一個ListBox或其他ItemsControl顯示數據列表,下方一個TextBlock顯示列表中選定的值,代碼大概是這樣的(做了簡化):

<Border Background="{TemplateBinding Background}"BorderBrush="{TemplateBinding BorderBrush}"BorderThickness="{TemplateBinding BorderThickness}"><StackPanel><ListBox ItemsSource="{Binding RelativeSource={RelativeSource TemplatedParent},Path=TimeDataSource.Months}"SelectedValue="{TemplateBinding Month}" VerticalContentAlignment="Top"></ListBox><TextBlock Text="{TemplateBinding Month}"/></StackPanel> </Border>

Month是后臺定義的依賴屬性,現在的問題是,ListBox拿到了數據(1到12個月),但下方的TextBlock卻顯示不出列表的SelectedValue,必須把它的代碼換成這樣才行:

<TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Month}"/>

用snoop抓取也會看到后面一種情形,Text屬性才能拿到值。顯然要查清楚問題所在必須研究一下TemplateBinding。

按照MSDN和網絡上看到的解釋,TemplateBinding主要用于模版,屬于優化的Binding但精簡了繼承內容引用和動態類型轉換等很多功能,它等效于:{Binding RelativeSource={RelativeSource TemplatedParent}}。看到這兒品味出什么了吧,對,類型轉換!它所綁定的依賴屬性Month是Int類型,而TextBlock的Text屬性是String類型,如果用普通Binding,WPF能自動幫你做轉換,而TemplateBinding就不行了。無獨有偶,幾個月前我寫過一個小控件,一個要求是輸入框(TextBox)前面的文本說明是可以設置的,比如“柜員賬號”或其他什么名稱,我定義的InputName屬性是String類型,用TemplateBinding和TextBlock綁在一起就可以正常運行。那就再定義一個String類型的依賴屬性,試試看:

public static readonly DependencyProperty MonthStringProperty =DependencyProperty.Register("MonthString", typeof(String), typeof(ControlTest),new FrameworkPropertyMetadata(DateTime.Now.Month.ToString()));public String MonthString{get { return GetValue(MonthStringProperty).ToString(); }set { SetValue(MonthStringProperty, value); }}

前臺Xaml如下:

<Border Background="{TemplateBinding Background}"BorderBrush="{TemplateBinding BorderBrush}"BorderThickness="{TemplateBinding BorderThickness}"><StackPanel><TextBlock Text="{TemplateBinding MonthString}"/><ListBox ItemsSource="{Binding RelativeSource={RelativeSource TemplatedParent},Path=TimeDataSource.Months}"SelectedValue="{TemplateBinding Month}" VerticalContentAlignment="Top"></ListBox><TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Month}"/></StackPanel></Border>

果然,數據能顯示了:

所以,可以得出:TemplateBinding的源和目標類型必須完全一致,如果它們之間需要類型轉換,只能改成{Binding RelativeSource}的形式,或者定義依賴屬性時注意一下類型,這里Month由于后面涉及一些計算必須定義為int。

轉載于:https://www.cnblogs.com/zxmoe992/archive/2013/06/08/3127030.html

總結

以上是生活随笔為你收集整理的为什么这儿TemplateBinding不起作用了—研究WPF Binding(一)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。